/*! 讯猫mccms */
$(function () {
    var nav = $("#navContainer"),
        main = $('#mainContainer');
    mccms.getHbs({
        hbsName: "nav",
        container: nav,
        callback: mccms.control
    }),
        // 缓存搜索表单缓存
        main.on('click', 'form.data-cache', function () {
            mccms.refreshForm()
        }),
        // 分页缓存
        main.on('click', '.data-cache .pageClick', function () {
            mccms.stepCache.pageNo = $(this).attr('pageno');
        }),
        main.on('click', '.data-cache #pageIndex', function () { //回到首页
            mccms.stepCache.pageNo = 1
        }),
        main.on('click', '.data-cache #pagePrev', function () { //上一页
            mccms.stepCache.pageNo = $('.laypage_curr').attr('pageno') - 1
        }),
        main.on('click', '.data-cache #pageLast', function () { //尾页
            mccms.stepCache.pageNo = $(this).prev().prev().attr('pageno')
        }),
        main.on('click', '.data-cache #pageNext', function () { //下一页
            mccms.stepCache.pageNo = parseInt($('.laypage_curr').attr('pageno')) + 1
        }),
        // 返回
        main.on('click', '#goBack', function () {
            mccms.goBack()
        }),
        main.on('click', '#gobackFromEdit', function () {
            mccms.gobackFromEdit()
        })
    // 返回
    main.on('click', '#back', function () {
        history.back()
    }),
        // tab跳转
        main.on('click', '#tabBar span', function () {
            $('#tabBar span').removeClass('current');
            $(this).addClass('current');
            mccms.goTo(mccms.getHash('nav'), mccms.getHash('hbs'), $(this).attr('data-tab'));
        }),
        // nav跳转
        nav.on('click', '.ajaxLoad', function (event) {
            // 添加选中样式
            /*$(".arrow-r").remove();*/
            mccms.cleanStep();
            mccms.goTo($(this).attr('href'));
            return false;
        }),
        // 修改密码
        $('.change-pwd').on('click', function () {
            mccms.goTo(mccms.getHash('nav'), 'passwordEdit');
        }),
        // 注销
        $('.logout').on('click', function () {
            location.replace('logout')
        }),
        // 移动端（宽度小于767px）响应式布局头部菜单按钮
        $(".Hui-nav-toggle").click(function () {
            $(".Hui-aside").slideToggle();
        });
    var resizeID;
    // 左侧菜单响应式
    $(window).resize(function () {
        clearTimeout(resizeID);
        resizeID = setTimeout(function () {
            if ($(window).width() >= 768) {
                $(".Hui-aside").show()
            }
        }, 300);
    }),
        //全选控制
        mccms.checkAll(),
        // hash改变时跳转到hash对应的页面
        $(window).on('hashchange', function () {
            mccms.control()

        })
});

// 公共方法，定义在mccms命名空间下
window.mccms = {
    /**
     * [domain 项目域名]
     * @type {Array}
     */
    domain: [location.pathname.replace(/\/[^/]*$/, ''), ''],
    /**
     * [templatePath 存放模板文件的url]
     * @type {Array}
     */
    templatePath: ["templates/"],
    /**
     * [step 缓存页面搜索跳页信息]
     * @type {Object}
     */
    stepCache: {
        id: undefined,
        form: {},
        pageNo: undefined,
        module: ['', '', '']
    },
    refreshForm: function () {
        var id = $('#mainContaine .cache-search').attr('id'),
            form = $('#mainContaine .cache-search').serialize().split(/[=&]/);
        mccms.stepCache.id = id;
        for (var i = 0, k = 0, j = form.length; i < j / 2; i++) {
            mccms.stepCache.form[form[k]] = $('#' + id + ' [name="' + form[k] + '"]').val();
        }
    },
    cleanStep: function () {
        mccms.stepCache = {
            id: undefined,
            form: {},
            pageNo: undefined,
            module: ['', '', '']
        }
    },
    refreshShow: function () {
        // 新选中的模块a元素
        var nav = mccms.getHash('nav'),
            tab = mccms.getHash('tab'),
            cache = mccms.stepCache,
            oldEle = $('#Huifold .selected'),
            navEle = $('[href="' + nav + '"]', '#Huifold');

        if ($('#Huifold').length > 0) {
            oldEle.removeClass('selected').next('dd').hide();
            $('.arrow-r').remove();
            $('.current').removeClass('current');
            // 后添
            navEle.find('h4').length > 0 ?
                navEle
                    .children('h4').addClass('selected current').append('<i class="arrow-r"></i>') // 加选中样式(->)
                :
                navEle
                    .parent().addClass('current').append('<i class="arrow-r"></i>') // 加选中样式(->)
                    .parent().parent().show() // 显示二级菜单
                    .siblings('h4').addClass('selected current'); // 选中一级菜单
        }
        // 移动端（宽度小于767px）响应式布局时，选择后收起菜单
        if ($(window).width() < 768) {
            $(".Hui-aside").slideToggle();
        }
        if ($('#tabBar').length > 0) {
            $('#tabBar span').removeClass('current');
            if (tab) {
                $('#tabBar span[data-tab = "' + tab + '"]').addClass('current');
            } else {
                $('#tabBar span').eq(0).addClass('current');
            }
        }
        if (cache.id && $('#' + cache.id).length > 0) {
            for (var each in cache.form) {
                $('#' + cache.id + ' [name="' + each + '"]').val(cache.form[each]);
            }
        }
    },
    /**
     * [module 菜单层级由高到低]
     * @type {Array}
     */
    module: ['nav', 'step', 'tab'],
    /**
     * [setHash 跳转，可继承比当前层级高的参数]
     * @param {[object]} options [跳转后的参数]
     */
    setHash: function (options) {
        var options = options || {},
            hash = '';
        for (var each in options) {
            (options[each] || options[each] === 0) && (hash += each + '=' + options[each] + '&')
        }
        hash = hash.substring(0, hash.length - 1) || '',
            window.location.hash = hash;
    },
    /**
     * [getHash 获取url的hash参数]
     * @param  {[string]} name      [需要获取的参数名，'all'为获取所有, 'module'获取module中不为空的对象]
     * @return {[string||obj]}      [参数名在hash中的对应值||包含hash中所有值的对象]
     */
    getHash: function (name) {
        var name = name || '',
            module = [],
            hash = window.location.hash.replace(/[^\d\&\=\_A-Za-z]/gi, ''),
            all = {};
        hash = hash ? hash.split(/[#=&]/) : [];
        for (i = 0, j = hash.length / 2, k = 0; i < j; i++) {
            if (hash[k + 1]) all[hash[k]] = hash[k + 1];
            k += 2;
        }
        ;
        for (i = 0, j = mccms.module.length; i < j; i++) {
            module[i] = all[mccms.module[i]] ? all[mccms.module[i]] : '';
        }
        ;
        name = name == 'all' ? all : name == 'module' ? module : all[name] || '';
        return name;
    },
    /*
     *[addHash 添加或改变hash参数]
     *name string hash的key
     *value string hash的值
     */
    addHash: function (name, value) {
        var options = mccms.getHash('all'),
            name = name || '',
            value = value || '';
        options[name] = value;
        mccms.setHash(options);
    },
    /*
     *[removeHash 删除hash参数]
     *name 删除hash的key
     */
    removeHash: function (name) {
        var options = mccms.getHash('all'),
            name = name || '';
        options[name] = '';
        mccms.setHash(options);
    },
    /**
     * [goTo 页面跳转]
     * @param  {[string]} nav [nav名]
     * @param  {[string]} step  [hbs名]
     * @param  {[string]} opt [需要tab名传字符串值,需要使用多个参数使用对象]
     */
    goTo: function (nav, step, opt) {
        var options = {}, //= mccms.getHash('all')
            tab = typeof(opt) == "string" ? opt : '',
            newopt = typeof(opt) == "object" ? opt : {};
        options[mccms.module[0]] = nav,
            options[mccms.module[1]] = step == nav ? '' : step;
        options[mccms.module[2]] = tab;
        newopt = $.extend(options, newopt);
        mccms.setHash(newopt);

    },
    /*
     *goBack:返回上级菜单
     */
    goBack: function (tabName) {
        var options = {};
        options[mccms.module[0]] = mccms.getHash(mccms.module[0]) || undefined,
            options[mccms.module[1]] = undefined,
            options[mccms.module[2]] = tabName || $(this).attr('data-tab') || undefined;
        mccms.setHash(options);

    },
    /*
     *gobackFromEdit:从编辑，查看页面返回

    */
    gobackFromEdit: function (tabName) {
        var options = {};
        options[mccms.module[0]] = mccms.getHash(mccms.module[0]) || undefined,
            options[mccms.module[1]] = undefined,
            options[mccms.module[2]] = tabName || $(this).attr('data-tab') || undefined;
        mccms.setHash(options);
        sessionStorage.setItem("backId", "1")
    },
    /*
     *resetHomePage: 刷新主页面方法
     */
    resetHomePage: function () {
        location.reload();
    },
    /**
     * [control nav与step hbs异步获取,tab为方法]
     * @return {[type]} [name]
     */
    control: function () {
        var hbsName = mccms.getHash(mccms.module[1]) || mccms.getHash(mccms.module[0]) || 'welcome',
            oldModule = mccms.stepCache.module,
            navCach = oldModule ?
                oldModule[0] :
                '',
            stepCache = oldModule ?
                oldModule[1] :
                '',
            tabCache = oldModule ?
                oldModule[1] :
                '',
            funName = mccms.getHash('tab');

        if (hbsName !== 'welcome' && navCach === mccms.getHash('nav') && stepCache == mccms.getHash('step')) {
            if (tabCache === funName) {
                return;
            }
            var newfun = funName ? new Function(funName + '()') : undefined;
            if (newfun && $.isFunction(newfun)) {
                newfun();
            }
        } else {
            mccms.getHbs({
                local: false,
                hbsName: hbsName,
                container: $('#mainContainer'),
                callback: funName ? new Function(funName + '()') : undefined
            })
        }
    },
    ajax: function (options) {
        if (options && window.ajaxLock === options.url) {
            return
        }
        ;
        var defaultOptions = {
                url: "",
                method: "POST",
                data: {},
                dataType: "json",
                cache: true,
                lock: false
            },
            options = options || {},
            flag = false,
            loadingLayerIndex;
        options = $.extend(defaultOptions, options),
            options.lock ? (window.ajaxLock = options.url) : (delete window.ajaxLock),
            options.url = options.url.indexOf('http') ? mccms.domain[0] + options.url : options.url,
            options.url = options.cache ? options.url : options.url.indexOf('?') === -1 ? options.url + '?_=' + new Date().getTime() : options.url + '&_=' + new Date().getTime();
        return $.ajax({
            url: options.url,
            method: options.method,
            data: options.data,
            dataType: options.dataType,
            beforeSend: function () {
                loadingLayerIndex = layer.load({shade: [0.8, '#393D49']});
                if (options.beforeSend && $.isFunction(options.beforeSend)) {
                    options.beforeSend();
                }
            },
            success: function (data, xhr) {
                if (data.status == 200 || data.status == 300 || data.status == 400) {
                    if (flag) mccms.step = {
                        form: [],
                        serialize: '',
                        page: '',
                        hash: ''
                    };
                    if (options.success && $.isFunction(options.success)) {
                        options.success(data);
                    }
                } else if (data.status == 600) {
                    location.href = location.origin + '/login';
                } else if (data.status == 700) {
                    layer.msg('您没有此操作的权限！', {time: 1500});
                } else {
                    layer.msg(data.message, {time: 1000});
                    // 业务错误处理...
                    if (options.errorStatus) options.errorStatus(data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.responseText.indexOf('mc_password') !== -1) { //section过期跳转首页
                    location.href = 'login'
                } else { // 服务器错误处理...
                    if (options.error && $.isFunction(options.error)) {
                        options.error(jqXHR);
                    }
                    layer.msg('操作失败！', {time: 1000});
                }
            },
            complete: function () {
                delete window.ajaxLock;
                layer.close(loadingLayerIndex);
                if (options.complete && $.isFunction(options.complete)) {
                    options.complete();
                }
            }
        });
    },
    /*
     * 编译页面上的模板并生成Html
     * opt: {
     *   local: 本地为true默认为false
     *   hbsName: 模板文件名或模板Id
     *   container: 模板容器
     *   isAppend: 是否将生成的html append到容器，默认为否，直接替换容器内容
     *   callback: 模板添加成功后回调
     *   error: 请求非本地模板页失败的提示或方法
     * }
     * */
    getHbs: function (opt) {
        var defaultOpt = {
                'local': false,
                'hbsName': 'welcome',
                'container': $('#mainContainer'),
                'isAppend': false,
                'callback': null,
                'error': null
            },
            opt = opt || {};
        opt = $.extend(defaultOpt, opt);
        if (opt.local && opt.hbsName && $("#" + opt.hbsName).length > 0) {
            var template = Handlebars.compile($("#" + opt.hbsName).html());
            if (opt.isAppend) {
                opt.container && opt.container.append(template(opt.data));
            } else {
                opt.container && opt.container.html(template(opt.data));
            }
            if (opt.callback && $.isFunction(opt.callback)) {
                opt.callback();
            }
            mccms.stepCache.module = [
                mccms.getHash('nav'),
                mccms.getHash('step')
            ]
        } else if (!opt.local) {
            $.ajax({
                url: mccms.templatePath[0] + opt.hbsName + ".hbs",
                method: "GET",
                success: function (tmpl) {
                    var template = Handlebars.compile(tmpl);
                    opt.container && opt.container.html(template(opt.data || {}));
                    mccms.refreshShow();
                    if (opt.callback && $.isFunction(opt.callback)) {
                        opt.callback();
                    }
                    mccms.stepCache.module = [
                        mccms.getHash('nav'),
                        mccms.getHash('step')
                    ]
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (opt.error && $.isFunction(opt.error)) {
                        opt.error();
                    }
                    mccms.cleanStep()
                }
            });
        } else {
            // 找不到本地模版错误提示
            console.error('未在模版' + (mccms.getHash('step') || mccms.getHash('nav') || 'welcome') + '.hbs中找到本地模版' + opt.hbsName + '，请检查！')
        }
    },
    /*
     * ajax分页
     * json:异步获取到的数据
     * pageCount：数据分页总数
     * pageNo：当前获取数据所在页数
     * fn:页面所在步骤方法，方法理应实现根据传入页码获取数据,并展示数据;
     * inputNum: 搜索时参数数组
     * eleId: 分页容器id 默认为layPage，适用于同一页面多个分页
     */
    pageHtml: function (json, fn, inputNum, eleId) {
        json.result = (typeof(json.result) == 'string') ? JSON.parse(json.result) : json.result;
        eleId = eleId || 'layPage';
        var data = '';
        var inputNum = inputNum;

        if (json.result.pageCount && json.result.pageCount != 1 && json.result.pageCount != 0) {
            if (json.result.pageCount <= 6) {
                for (var i = 1; i < json.result.pageCount + 1; i++) {
                    data += '<a class="pageClick" pageNo=' + i + '>' + i + '</a>';
                }
            } else if (json.result.pageNo > json.result.pageCount - 3) {
                data += '<a class="pageClick" pageNo="1">1</a>...';
                for (var i = json.result.pageCount - 3; i <= json.result.pageCount; i++) {
                    data += '<a class="pageClick" pageNo=' + i + '>' + i + '</a>';
                }
            } else if (json.result.pageNo < 4) {
                for (var i = 1; i < 6; i++) {
                    data += '<a class="pageClick" pageNo=' + i + '>' + i + '</a>';
                }
                data += '...<a class="pageClick" pageNo=' + json.result.pageCount + '>' + json.result.pageCount + '</a>';
            } else {
                data += '<a class="pageClick" pageNo="1">1</a>';
                data += json.result.pageNo - 2 == 2 ? '' : '...';
                data += '<a class="pageClick" pageNo=' + (json.result.pageNo - 2) + '>' + (json.result.pageNo - 2) + '</a>';
                data += '<a class="pageClick" pageNo=' + (json.result.pageNo - 1) + '>' + (json.result.pageNo - 1) + '</a>';
                data += '<a class="pageClick" pageNo=' + json.result.pageNo + '>' + json.result.pageNo + '</a>';
                data += '<a class="pageClick" pageNo=' + (json.result.pageNo + 1) + '>' + (json.result.pageNo + 1) + '</a>';
                data += '<a class="pageClick" pageNo=' + (json.result.pageNo + 2) + '>' + (json.result.pageNo + 2) + '</a>';
                data += json.result.pageNo + 3 == json.result.pageCount ? '' : '...';
                data += '<a class="pageClick" pageNo=' + json.result.pageCount + '>' + json.result.pageCount + '</a>';
            }
            if (json.result.pageNo == 1) {
                $("#" + eleId).html('<table class="pager" pageNo="' + json.result.pageNo + '"><tbody><tr><td width="60%">' + data + '<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
            } else if (json.result.pageCount == json.result.pageNo) {
                $("#" + eleId).html('<table class="pager" pageNo="' + json.result.pageNo + '"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>' + data + '</td></tr></tbody></table>');
            } else {
                $("#" + eleId).html('<table class="pager" pageNo="' + json.result.pageNo + '"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>' + data + '<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
            }
            $("a[pageNo=" + json.result.pageNo + "]").addClass("laypage_curr").removeClass("pageClick");
            $("#" + eleId).off().on('click', '#pageIndex', function (event) {
                fn(1, inputNum[0], inputNum[1], inputNum[2]); //inputNum搜索时传递的参数数组
            });
            $("#" + eleId).on('click', '#pageLast', function (event) {
                fn(json.result.pageCount, inputNum[0], inputNum[1], inputNum[2]); //inputNum搜索时传递的参数数组
            });
            $("#" + eleId).on('click', '#pagePrev', function (event) {
                fn((parseInt(json.result.pageNo) - 1), inputNum[0], inputNum[1], inputNum[2]); //inputNum搜索时传递的参数数组
            });
            $("#" + eleId).on('click', '#pageNext', function (event) {
                fn((parseInt(json.result.pageNo) + 1), inputNum[0], inputNum[1], inputNum[2]); //inputNum搜索时传递的参数数组
            });
            $("#" + eleId).on('click', '.pageClick', function (event) {
                fn(parseInt($(this).attr('pageno')), inputNum[0], inputNum[1], inputNum[2]); //inputNum搜索时传递的参数数组
            });
        } else {
            $("#" + eleId).html('');
        }
    },
    /*
     *对选中的列表进行操作
     *msg.flag : true弹层提示,默认为true,提示
     *msg.name : 操作名称，不需要弹层可不传
     *msg.title : 批量操作的对象名称，批量操作时使用
     *msg.sub : 无data也可上传，针对url带参上传方式，默认false
     *msg.url : 操作对应的接口
     *msg.method : 不传入默认为get
     *msg.data : 操作需要传递给接口的参数,不写默认为空
     *msg.fn : 刷新列表的方法
     *msg.pageNo: 刷新跳转到的页码(默认刷新到操作前页码)
     */
    operation: function (msg) {
        var defaultOptions = {
                method: "GET",
                flag: true,
                name: '',
                title: '',
                data: '',
                sub: false
            },
            msg = $.extend(defaultOptions, msg);

        if (!msg.pageNo) msg.pageNo = ($('.laypage_curr')) ? $('.laypage_curr').attr('pageno') : '1';
        if (msg.flag) {
            if (msg.data || msg.sub) {
                layer.confirm('确定要' + msg.name + '吗？', {
                    time: 0,
                    btn: ['确定', '取消'],
                    yes: function (index) {
                        if (msg.name.indexOf('删除') >= 0) {
                            if ($('#checkList .checkbox').length != 0 && $('#checkList .checkbox').length == $('#checkList .checkbox:checked').length && msg.pageNo > 1) {
                                msg.pageNo = msg.pageNo - 1;
                            } else if ($('table').eq(0).find('tbody tr').length == 1) {
                                msg.pageNo = msg.pageNo - 1;
                            }
                        }
                        ;
                        layer.close(index);
                        mccms.ajax({
                            url: msg.url,
                            method: msg.method,
                            data: msg.data,
                            success: function (data) {
                                if (data.result == 'failure') {
                                    layer.msg(data.message)
                                } else {
                                    layer.msg("删除成功")
                                }


                                if ($('input.checkbox')[0]) $('input.checkbox')[0].checked = false;
                                if (msg.fn && $.isFunction(msg.fn)) {
                                    msg.fn(msg.pageNo);
                                }
                            }
                        });
                    }
                });
            } else {
                layer.open({
                    type: 1, //page层
                    area: ['220px', '140px'],
                    title: '提示',
                    btn: "ok",
                    shade: 0.5, //遮罩透明度
                    moveType: 1, //拖拽风格，0是默认，1是传统拖动
                    shift: 0, //0-6的动画形式，-1不开启
                    content: '<div style="padding:10px 22px 0;">请先选择需要' + msg.name + '的' + msg.title + '</div>'
                });
            }
        } else {
            mccms.ajax({
                url: msg.url,
                method: msg.method,
                data: msg.data,
                success: function () {
                    $('input.checkbox')[0].checked = false;
                    if (msg.fn && $.isFunction(msg.fn)) {
                        msg.fn(msg.pageNo);
                    }
                }
            });
        }
    },
    /*
     *为列表绑定全选事件
     *包裹表单需要有id,类名包含form-list
     *input的class均为checkbox
     */
    checkAll: function () {
        $(document).on('click', '.form-list input.checkbox', function (event) {
            var flag = true,
                id = $(this).parents('form').attr('id'),
                checkbox = $('#' + id + ' input.checkbox')
            checkall = checkbox[0],
                that = $(this)[0];
            if (that == checkall) {
                flag = that.checked;
                checkbox.each(function (index, el) {
                    $(this)[0].checked = flag;
                })
            } else {
                checkbox.each(function (index, el) {
                    if ($(this)[0] != checkall) flag = ($(this)[0].checked == false) ? false : flag;
                })
                checkall.checked = flag
            }
        });
    },
    /*
     * 作用：优化时间段选择（根据起始时间限制结束框最小时间，根据结束时间限制起始框最大时间）
     * 起始id：startTime，结束id：endTime
     */
    endtime: function (opt, date) {
        var defaultopt = {
                min: data || '',
                choose: function (dates) {
                    mccms.endtime(dates, opt);
                }
            },
            opt = $.extend(defaultopt, opt);
        $('#endTime').off().on('click', function () {
            laydate(opt)
        });
    },
    starttime: function (opt, date) {
        var defaultopt = {
                max: data || '',
                choose: function (dates) {
                    mccms.endtime(dates, opt);
                }
            },
            opt = $.extend(defaultopt, opt);
        $('#startTime').off().on('click', function () {
            laydate(opt)
        });
    },
    /**
     *图片上传&文件上传(默认为提交图片)
     *options{
     *iptid: string  文件上传input标签的id值【默认为:'doc'】;
     *imgid: string  用于展示预览图片的img标签的id值【默认为:'',dom结构需要按固定格式】【tip:如果需要兼容低版本ie,img标签需要有外层容器】;
     *srcid: string  提交上传文件地址的input的id值【默认为:'src'】;
     *url:   string  提交文件的的接口【默认为:'/base/imageUpload'】;
     *size:  number  提文件的最大限制【默认为:15】【tip:单位为M】;
     *reg:   RegExp||Boole  文件后缀限制的正则表达式;【默认为：图片后缀检查正则】【tip: 不想验证后缀请设为false】;
     *type:  string  文件类型文字提示【默认: '图片'】;
     *data:  Object  附带参数【默认:有 true】;
     *success function 成功回调方法;
     *error  function 错误回调方法;
     *lock:  Boole   文件上传就绪才能进行下一个上传操作【默认为：否 false】;
     *change:  Boole   文件元素改变就进行上传？【默认为：否 false】;
     *}
     */
    upload: function (options) {
        var defaultOptions = {
                lock: false,
                iptid: "doc",
                srcid: "src",
                url: "/base/imageUpload",
                imgid: "",
                type: "图片",
                data: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                change: true,
                size: "15",
                reg: new RegExp('\\.gif$|\\.png$|\\.jpg$|\\.bmp$|\\.jpeg$', 'i')
            },
            opt = $.extend(defaultOptions, options),
            fileName = $("#" + opt.iptid).val(),
            iptEle = $("#" + opt.iptid),
            srcEle = $("#" + opt.srcid),
            imgEle = opt.imgid ? $("#" + opt.imgid) : iptEle.parent().find('img'),
            imgOldSrc = imgEle.length > 0 ? imgEle.attr('src') : '';
        if (window.imglock) {
            layer.msg('请等待另一个' + opt.type + '上传完成', {time: 1000});
            return;
        } else if (opt.size && document.getElementById(opt.iptid).files[0].size > opt.size * 1024 * 1024) {
            layer.msg('不能上传超过' + opt.size + 'M的' + opt.type, {time: 1000});
            return;
        } else if (opt.reg && !opt.reg.test(fileName.toLowerCase())) {
            layer.msg('请确保上传文件为' + opt.type, {time: 1000});
            return;
        } else {
            if (opt.lock === true) {
                window.imglock = true;
            }
            if (opt.type === "图片") {
                mccms.setImagePreview(opt.iptid, opt.imgid);
            }
            iptEle.next('img').length > 0 ?
                iptEle.next('img').show() :
                iptEle.after('<img class="loadFile" style="width: 100px;height: 7px" src="img/loadFile.gif" alt="正在上传">');
            $.ajaxFileUpload({
                url: mccms.domain[0] + opt.url,
                data: opt.data,
                secureuri: false, //一般设置为false
                fileElementId: opt.iptid,
                dataType: 'json', //返回值类型 一般设置为json
                success: function (data, status, headers, config) { //服务器成功响应处理函数
                    iptEle.next('img').show();
                    $("img.loadFile").hide();
                    srcEle.val(data.result);
                    if (opt.change) {
                        $("#" + opt.iptid).off().on('change', function () {
                            mccms.upload(opt);
                        })
                    }
                    typeof(opt.success) === "function" && opt.success(data);
                    delete window.imglock;
                },
                error: function (data, status, headers, config) { //服务器响应失败处理函数
                    iptEle.next('img').show();
                    data.result && layer.msg(data.result, {time: 1000});
                    if (opt.type === "图片") {
                        imgEle.attr('src', imgOldSrc);
                    }
                    if (opt.change) {
                        $("#" + opt.iptid).off().on('change', function () {
                            mccms.upload(opt);
                        })
                    }
                    typeof(opt.error) === "function" && opt.error(data);
                    delete window.imglock;
                }
            })
        }
    },
    /*
     *图片预览
     *inputId：input的id值,默认为：'doc';
     *imgId：img的id值;【默认为：'',dom结构需要按固定格式】
     *如果需要兼容低版本ie,需要给img标签添加外层容器
     */
    setImagePreview: function (inputId, imgid) {
        var docObj = document.getElementById(inputId) || document.getElementById('doc'),
            fileName = docObj.value;
        if (imgid !== '') {
            var imgObjPreview = document.getElementById(imgid),
                imgCotent = imgObjPreview.parentNode;
        } else {
            var imgCotent = (docObj.previousSibling.nodeType == 1) ? docObj.previousSibling : docObj.previousSibling.previousSibling,
                imgObjPreview = (imgCotent.firstChild.nodeType == 1) ? imgCotent.firstChild : imgCotent.firstChild.nextSibling;
        }
        if (docObj.files && docObj.files[0]) {
            //火狐下，直接设img属性 
            //imgObjPreview.src = docObj.files[0].getAsDataURL(); 
            imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
        } else {
            //IE下，使用滤镜  
            docObj.select();
            docObj.blur();
            var imgSrc = document.selection.createRange().text;
            var localImagId = imgCotent;
            //设置初始大小  
            localImagId.style.width = docObj.currentStyle.width;
            localImagId.style.height = docObj.currentStyle.Height;
            //图片异常的捕捉，防止用户修改后缀来伪造图片
            try {
                localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
            } catch (e) {
                layer.msg("您上传的图片格式不正确，请重新选择！", {time: 1000});
                return false;
            }
            imgObjPreview.style.display = 'none';
            document.selection.empty();
        }
        return true;
    },
    /*
     * 配置导航栏图标
     */
    styleIcon: {
        '基本配置': "Hui-iconfont-user-group",
        '栏目配置': "Hui-iconfont-menu",
        '系统配置': "Hui-iconfont-manage",
        'MCGT': "Hui-iconfont-manage2"
    }
}
/*公共方法属性控制*/
Object.defineProperty(window, 'mccms', {configurable: false, writable: false});
Object.defineProperty(mccms, 'ajax', {configurable: false, writable: false});
// Object.defineProperty(mccms, 'step', {configurable : true, writable : true});

// 粗体
Handlebars.registerHelper("mccmsEm", function (str, name) {
    return new Handlebars.SafeString("<span class='" + name + "'>" + str + "</span>");
});

// 相等则显示
Handlebars.registerHelper("mccmsShowIfEqual", function (value, value2, options) {
    if (value == value2) {
        return options.fn(this);
    }
    return options.inverse(this);
});

// 加减乘除运算
Handlebars.registerHelper("Math", function (num1, operator, num2) {
    var result,
        num1 = +num1,
        num2 = +num2;
    switch (operator) {
        case "+":
            result = num1 + num2;
            break;
        case "-":
            result = num1 - num2;
            break;
        case "*":
            result = num1 * num2;
            break;
        case "/":
            result = num1 / num2;
            break;
    }

    return result;
});

// 下拉框选择
Handlebars.registerHelper('mccmsSelect', function (value, options) {
    var element = $('<select />').html(options.fn(this));
    element.find('[value="' + value + '"]').attr({'selected': 'selected'});
    return element.html();
});

// 单选框选择
Handlebars.registerHelper("mccmsChecked", function (value, currentValue) {
    if (value == currentValue) {
        return "checked"
    } else {
        return "";
    }
});
// 判断传值为true返回selected
Handlebars.registerHelper("mccmsSelectedE", function (value, currentValue) {
    if (value == true) {
        return "selected"
    } else {
        return "";
    }
});

// select选中判断
Handlebars.registerHelper('isSelect', function (result, options) {
    var htmlStr = '';
    for (var i = 0; i < result.ntAuthorities.length; i++) {
        var item = result.ntAuthorities[i];
        var flag = false;
        if (result.ntRoles) {
            for (var j = 0; j < result.ntRoles.ntAuthorities.length; j++) {
                if (result.ntRoles) {
                    var itemJ = result.ntRoles.ntAuthorities[j];
                    if (item.id == itemJ.id) {
                        flag = true;
                        break;
                    }
                } else {
                    break;
                }
            }
        }
        if (flag) {
            htmlStr += '<option value="' + item.id + '" selected>' + item.name + '</option>';
        } else {
            htmlStr += '<option value="' + item.id + '">' + item.name + '</option>';
        }
    }

    return new Handlebars.SafeString(htmlStr);
});

// 频道列表频道类型select选中判断
Handlebars.registerHelper('isSelectType', function (result, options) {
    var htmlStr = '';
    if (result && result.flag) {
        for (var i = 0; i < result.ntAuthorities.length; i++) {
            var item = result.ntAuthorities[i];
            var flag = false;
            if (result.syChannelinfo.ntAuthorities) {
                var itemJ = result.syChannelinfo.ntAuthorities;
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.name + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.name + '</option>';

            }
        }
    } else {
        for (var j = 0; j < result.ntAuthorities.length; j++) {
            var authorityItem = result.ntAuthorities[j];
            htmlStr += '<option value="' + authorityItem.id + '">' + authorityItem.name + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 频道列表上级频道select选中判断
Handlebars.registerHelper('isSelectSuperior', function (result, options) {
    var htmlStr = '';
    if (result && result.flag) {
        if (result.syChannelinfo.syChannelinfo == null) {
            htmlStr += '<option value="">一级频道</option>';
        }
        for (var i = 0; i < result.superiorSyChannels.length; i++) {
            var item = result.superiorSyChannels[i];
            var flag = false;
            if (result.syChannelinfo.syChannelinfo) {
                var itemJ = result.syChannelinfo.syChannelinfo;
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.channelname + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.channelname + '</option>';

            }
        }
    } else {
        htmlStr += '<option value="">一级频道</option>';
        for (var j = 0; j < result.superiorSyChannels.length; j++) {
            var authorityItem = result.superiorSyChannels[j];
            htmlStr += '<option value="' + authorityItem.id + '">' + authorityItem.channelname + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 直/点播视频列表所属频道select选中判断
Handlebars.registerHelper('isSelectChannel', function (result, options) {
    var htmlStr = '';
    if (result.flag) {
        for (var i = 0; i < result.syChannelinfos.length; i++) {
            var item = result.syChannelinfos[i];
            var flag = false;
            if (result.syPlayInfo.syChannelinfo) {
                var itemJ = result.syPlayInfo.syChannelinfo;
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.channelname + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.channelname + '</option>';

            }
        }
    } else {
        for (var j = 0; j < result.length; j++) {
            var authorityItem = result[j];
            htmlStr += '<option value="' + authorityItem.id + '">' + authorityItem.channelname + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 直/点播视频列表所属频道select选择项
Handlebars.registerHelper('selectChannel', function (result, options) {
    var htmlStr = '<option value="">所有频道</option>';
    for (var i = 0; i < result.length; i++) {
        var item = result[i];
        htmlStr += '<option value="' + item.id + '">' + item.channelname + '</option>';
    }
    return new Handlebars.SafeString(htmlStr);
});

// 直/点播视频列表所属频道select选中判断
Handlebars.registerHelper('isSelectChannel', function (result, options) {
    var htmlStr = '';
    if (result.flag) {
        for (var i = 0; i < result.syChannelinfos.length; i++) {
            var item = result.syChannelinfos[i];
            var flag = false;
            if (result.syPlayInfo.syChannelinfo) {
                var itemJ = result.syPlayInfo.syChannelinfo;
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.channelname + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.channelname + '</option>';

            }
        }
    } else {
        for (var j = 0; j < result.length; j++) {
            var authorityItem = result[j];
            htmlStr += '<option value="' + authorityItem.id + '">' + authorityItem.channelname + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 互动竞猜列表所属频道select选中判断
Handlebars.registerHelper('isGuessChannel', function (result, options) {
    var htmlStr = '';
    if (result.flag) {
        for (var i = 0; i < result.syChannelinfos.length; i++) {
            var item = result.syChannelinfos[i];
            var flag = false;
            if (result.syGuessinfo.syChannelinfo) {
                var itemJ = result.syGuessinfo.syChannelinfo;
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.channelname + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.channelname + '</option>';

            }
        }
    } else {
        for (var j = 0; j < result.length; j++) {
            var authorityItem = result[j];
            htmlStr += '<option value="' + authorityItem.id + '">' + authorityItem.channelname + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 开启平台多种可能选框选择
Handlebars.registerHelper('CheckedPlatform', function (result, value) {
    if (result) {
        if (result.indexOf(value) > 0 || result.indexOf(value) == 0) {
            return 'checked'
        } else {
            return '';
        }
    }
});

// 去除第一个字符，作用于图片路径
Handlebars.registerHelper('forImg', function (value) {
    var value = value || ''
    if (value) {
        value = (value.charAt(0) == '/') ? value.substring(1) : value;
        return value;
    } else {
        return '';
    }
});

// 字符串限制17个
Handlebars.registerHelper('cutString', function (value) {
    value = (value) ? value + '' : '';
    if (value.length > 10) return value.substring(0, 17) + '…'
    else return value;
});

// 根据timestamp显示 xx分钟前
Handlebars.registerHelper('timeFromNow', function (timestamp) {
    var now = new Date().getTime();
    var timeDiff = now - timestamp;
    var timeFromNow = '刚刚';
    // 30秒之内显示刚刚
    if (timeDiff < 30 * 1000) {
        timeFromNow = '刚刚';
    }
    // 1小时内显示 xx分钟前
    else if (timeDiff < 60 * 60 * 1000) {
        timeFromNow = Math.ceil(timeDiff / 1000 / 60) + '分钟前';
    }
    // 24小时内显示 xx小时前
    else if (timeDiff < 24 * 60 * 60 * 1000) {
        timeFromNow = Math.ceil(timeDiff / 1000 / 60 / 60) + '小时前';
    }
    // 其他情况写 xx天前
    else {
        timeFromNow = Math.ceil(timeDiff / 1000 / 60 / 60 / 24) + '天前';
    }
    return timeFromNow;
});

// 显示表情
Handlebars.registerHelper("mccmsShowEmotion", function (value, options) {
    var str = value;
    var matches = value.match(/(\[[^\[\)]+\])/g);
    var emotions = JSON.parse(sessionStorage.getItem('emtion-array'));

    if (matches && matches.length > 0) {
        for (var i = 0; i < matches.length; i++) {
            var match = matches[i];

            for (var j = 0; j < emotions.length; j++) {
                var emotion = emotions[j];

                if (emotion.code == match) {
                    str = str.replace(match, '<img src="' + emotion.file + '" alt="' + emotion.name + '" class="emotion__inline-image">');
                }
            }
        }
    }
    return new Handlebars.SafeString(str);
});

// value2存在value则显示
Handlebars.registerHelper("checkShow", function (value, value2, options) {
    if (value) {
        if (value.indexOf(value2) > 0 || value.indexOf(value2) == 0) {
            return options.fn(this);
        }
    }
    return options.inverse(this);
});

// 按系统消息类型显示对应文字
Handlebars.registerHelper("showSystemMessageType", function (value, options) {
    var messageType = 'N/A';

    switch (parseInt(value)) {
        case 1:
            messageType = '预约';
            break;
        case 2:
            messageType = '竞猜';
            break;
        case 3:
            messageType = '充值';
            break;
        case 4:
            messageType = '签到';
            break;
        case 5:
            messageType = '短信';
            break;
    }


    return messageType;
});

// 消息推送角色select选中判断
Handlebars.registerHelper('isSelectRole', function (result, options) {
    var htmlStr = '';
    if (result.flag) {
        for (var i = 0; i < result.Role.length; i++) {
            var item = result.Role[i];
            var flag = false;
            if (result.pushMess.pushRoles) {
                var itemJ = result.pushMess.pushRoles[0];
                if (item.id == itemJ.id) {
                    flag = true;
                }
            }
            if (flag) {
                htmlStr += '<option value="' + item.id + '" selected>' + item.name + '</option>';
            } else {
                htmlStr += '<option value="' + item.id + '">' + item.name + '</option>';

            }
        }
    } else {
        for (var j = 0; j < result.length; j++) {
            var roleItem = result[j];
            htmlStr += '<option value="' + roleItem.id + '">' + roleItem.name + '</option>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 消息推送角色checkbox选中判断
Handlebars.registerHelper('isCheckRole', function (result, options) {
    var htmlStr = '';
    if (result.flag) {
        for (var i = 0; i < result.Role.length; i++) {
            var item = result.Role[i];
            var flag = false;
            if (result.pushMess.pushRoles) {
                var itemJ = result.pushMess.pushRoles;
                for (var j = 0; j < itemJ.length; j++) {
                    if (item.id == itemJ[j].id) {
                        flag = true;
                    }
                }
            }
            if (flag) {
                htmlStr += '<div class="check-box">' +
                    '<input type="checkbox" id="checkbox-' + i + '" value="' + item.id + '" checked> ' +
                    '<label for="checkbox-' + i + '">' + item.name + '</label>' +
                    '</div>';
            } else {
                htmlStr += '<div class="check-box">' +
                    '<input type="checkbox" id="checkbox-' + i + '" value="' + item.id + '"> ' +
                    '<label for="checkbox-' + i + '">' + item.name + '</label>' +
                    '</div>';

            }
        }
    } else {
        for (var k = 0; k < result.length; k++) {
            var roleItem = result[k];
            htmlStr += '<div class="check-box">' +
                '<input type="checkbox" id="checkbox-' + k + '" value="' + roleItem.id + '"> ' +
                '<label for="checkbox-' + k + '">' + roleItem.name + '</label>' +
                '</div>';
        }
    }
    return new Handlebars.SafeString(htmlStr);
});

// 去除日期字段时间
Handlebars.registerHelper("cutTime", function (value) {
    if (value) {
        return value.substring(0, 10);
    }
});

// 时间戳转日期字符串
Handlebars.registerHelper("timestampToDateString", function (timestamp) {
    if (timestamp == null || typeof(timestamp) == 'string') {
        return timestamp;
    } else {
        var d = new Date(timestamp);

        return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + (d.getHours() < 10 ? '0' + d.getHours() : d.getHours()) + ':' + (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()) + ':' + (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds());
    }
});
// 时间戳转日期字符串
Handlebars.registerHelper("timestampToDateString2", function (timestamp) {
    if (timestamp == null || typeof(timestamp) == 'string') {
        return timestamp;
    } else {
        var d = new Date(timestamp);

        return d.getFullYear() + '-' + (d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1)) + '-' + (d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate()) + ' ' + (d.getHours() < 10 ? '0' + d.getHours() : d.getHours()) + ':' + (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()) + ':' + (d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds());
    }
});

// 后台获取前台图片时，添加域名前缀
Handlebars.registerHelper("imgDomain", function (value) {

    return new Handlebars.SafeString(mccms.appDomain + value);
});

// 获取图片时，添加图片绝对路径前缀
Handlebars.registerHelper("imgSrc", function (value) {
    var value = value || '';
    if (value) {
        value = (value.charAt(0) == '/') ? value.substring(1) : value;
        return new Handlebars.SafeString(mccms.picDomain + value);
    } else {
        return '';
    }
});

// 消息推送短信模板select选择项
Handlebars.registerHelper('selectMessage', function (result, options) {
    if (result) {
        var htmlStr = '';
        for (var i = 0; i < result.length; i++) {
            var item = result[i];
            htmlStr += '<option value="' + item.messId + '">' + item.messId + '</option>';
        }
        return new Handlebars.SafeString(htmlStr);
    }
});

// 聊天监控获取新评论时，用新数据同步旧评论的拉黑、禁言状态
Handlebars.registerHelper('updateMonitorStatus', function (memberId, blackStatus, muteStatus) {
    $('.chat-message-operation-black[memberid="' + memberId + '"]').attr('status', blackStatus).val(blackStatus == 'Y' ? '取消拉黑' : '拉黑');
    $('.chat-message-operation-mute[memberid="' + memberId + '"]').attr('muteStatus', muteStatus).val(muteStatus == 'Y' ? '取消禁言' : '禁言');
});
/* Jquery plugin START */
/*
 * 表单验证，通过给需要验证的输入控件（input、select等）添加类实现验证规则设定
 *
 * 类名格式：mccms-validate-验证规则[?参数]
 * 如：
 * 非空 mccms-validate-required
 * 最大长度10字符 mccms-validate-maxlength?10
 * 输入值大于1小于10范围内 mccms-validate-range?[1,10]
 * ele.mcFormValide()绑定表单验证 
 * ele.validate().resetForm()重置表单
 * */
$.fn.mcFormValide = function (options) {
    var defaultOptions = {};
    options = $.extend(defaultOptions, options);
    return this.each(function () {
        var self = $(this);
        // 需要验证的空间元素，包含mccms-validate-*类的空间元素
        var inputEles = self.find('[class*="mccms-validate-"]');
        var rules = {};
        for (var i = 0; i < inputEles.length; i++) {
            var inputEle = inputEles.eq(i);
            // var inputClassList = inputEles[i].classList;
            var inputClassList = inputEle.attr('class').split(/\s+/);

            var rule = {};
            var regExpPrefix = /^mccms-validate-/; // 前缀
            var regExpSuffix = /\?\S+$/; // 后缀
            for (var j = 0; j < inputClassList.length; j++) {
                var clazz = inputClassList[j];

                var ruleName = clazz.replace(regExpPrefix, '').replace(regExpSuffix, "");

                if (regExpPrefix.test(clazz)) {
                    // 规则带参数
                    if (regExpSuffix.test(clazz)) {
                        rule[ruleName] = clazz.match(regExpSuffix)[0].replace("?", ""); // 把”？“去掉
                    }
                    // 不带参数直接给true
                    else {
                        rule[ruleName] = true;
                    }
                }
            }

            rules[inputEle.attr('name')] = rule;
        }

        self.validate({
            onsubmit: false,
            errorClass: 'error-lab',
            errorElement: "span",
            rules: rules
        });
    });
};

jQuery.validator.addMethod("stringCheck", function (value, element) {
    var reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    return this.optional(element) || reg.test(value);
}, "只包括中文字、英文字母、数字和下划线,不能以下划线开头结尾");

jQuery.validator.addMethod("stringCheck2", function (value, element) {
    var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    return this.optional(element) || reg.test(value);
}, "不能输入特殊字符");

jQuery.validator.addMethod("whitespaceCheck", function (value, element) {
    var reg = /^\s+$/;
    return this.optional(element) || !reg.test(value);
}, "不能只包含空格或回车");

jQuery.validator.addMethod("isMobile", function (value, element) {
    var length = value.length;
    return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value));
}, "请正确填写您的手机号码");

jQuery.validator.addMethod("isMobile2", function (value, element) {
    return this.optional(element) || (/^[1]{1}\d{10}$/).test(value);
}, "请正确填写您的手机号码");

jQuery.validator.addMethod("isPhone", function (value, element) {
    return this.optional(element) || /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/.test(value);
}, "请填写正确的电话号码");

jQuery.validator.addMethod("telephone", function (value, element) {
    return this.optional(element) || ((/^[0-9]{0,4}[-]{0,1}[0-9]*$/).test(value));
}, "请填写正确的电话号码");

jQuery.validator.addMethod("isPath", function (value, element) {
    var reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    return this.optional(element) || reg.test(value);
}, "请填写正确的路径");
jQuery.validator.addMethod("stringCheck3", function (value, element) {
    /*var reg = /^[(-//d+)|(0+)]$/;
    return this.optional(element) || reg.test(value);*/
    if (value < 0) {
        return false
    } else {
        return true
    }
}, "请输入正数"); //非负正整数
jQuery.validator.addMethod("stringCheck4", function (value, element) {
    /*var reg = /^[(-//d+)|(0+)]$/;
    return this.optional(element) || reg.test(value);*/
    if (!value) {
        return false
    } else {
        return true
    }
}, "必填字段"); //非负正整数

jQuery.validator.addMethod("Id_number", function (value, element) {
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return this.optional(element) || reg.test(value);
}, "请输入正确的证件号码");
// 自定义验证提示 
$.extend($.validator.messages, {
    required: "*必填字段",
    remote: "请修正该字段",
    email: "请输入正确格式的电子邮件",
    url: "请输入合法的网址",
    date: "请输入合法的日期",
    dateISO: "请输入合法的日期 (ISO).",
    number: "请输入合法的数字",
    digits: "只能输入整数",
    creditcard: "请输入合法的信用卡号",
    equalTo: "两次密码输入不一致",
    accept: "请输入拥有合法后缀名的字符串",
    maxlength: $.validator.format("请输入一个长度最多为 {0} 的字符串"),
    minlength: $.validator.format("请输入一个长度最少为 {0} 的字符串"),
    rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
    range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
    max: $.validator.format("请输入一个最大为 {0} 的值"),
    min: $.validator.format("请输入一个最小为 {0} 的值")
});
/* Jquery plugin END */


/*
 * 点击数据项，整个数据条添加背景色
 * id 表格数据容器的id
 * 
 */
function tdAddBg(id) {
    var $Id = $('#' + id + " td");
    $Id.on("click", function () {
        $(this).parent('tr').addClass("bg-C1C1C1 color-fff").siblings().removeClass('bg-C1C1C1 color-fff');
    })

}

/*锚点定位，点击导航栏滚动到相应内容块
 * div+i 内容块id须为div+数字，如div1，div2
 * 
 * 
 */
function scrollToBox(id) {
    var $Id = $("#" + id).children();
    $Id.each(function (i, v) {
        $(this).on('click', function () {
            $(this).addClass('active').siblings().removeClass('active')
            var dHeight = document.getElementById("div" + (i + 1)).offsetTop - 110
            $('#mainContainer').scrollTop("").scrollTop(dHeight)
        })

    })
}

/*--角色管理--*/

//列表
function roleManagement() {
    var pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        getList = function (pageNo, pageSize) {
            //给栏目表录入数据
            mccms.ajax({
                url: "/role/getRoleAll",
                method: "GET",
                cache: false,
                data: {
                    "pageNo": pageNo,
                    "pageSize": pageSize
                },
                success: function (json) {
                    //分页方法
                    PagingMethods(pageNo, pageSize, json, getList)

                    mccms.getHbs({ //将数据打包到模版丢进容器
                        local: true,
                        hbsName: "navMain",
                        container: $("#pathContainer")
                    });

                    mccms.getHbs({ //将数据打包到模版丢进容器
                        local: true,
                        hbsName: "getColumnTableData",
                        container: $("#ColumnTableData"),
                        data: json
                    });

                    $("#roleManagement").show();
                    $("#onClickDataTable").hide();
                    $('.btn_add').show();

                    //多出字数显示为省略号
                    $(".ellipsis").each(function () {
                        if ($(this).text().length > 80) {
                            var text = $(this).text().substring(0, 80) + "...";
                            $(this).text(text);
                        }
                    })
                }
            })
        }
    getList(pageNo, pageSize)
}

//查看
function checkDataRole(obj) {
    var roleName = $(obj).parents("tr").attr("name");
    var roleId = $(obj).parents("tr").attr("getId");
    mccms.ajax({
        url: "/role/getRole/" + $(obj).parents("tr").attr("getId"), //需要添加参数，看接口需要
        method: "GET",
        cache: false,
        success: function (json) {
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navCheck",
                container: $("#pathContainer")
            });

            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getCheckDataRole",
                container: $("#onClickDataTable"),
                data: json
            });
            /*  $("#roleManagement").hide();
              $("#onClickDataTable").show();
              $('.btn_add').hide();*/

            var list = [];
            for (var i = 0; i < json.result.permissions.length; i++) {
                list.push(json.result.permissions[i].id);
            }
            editDataRoleAll(list, json, roleId, roleName, '1');
            $('.treenode_check').remove();
        }
    })
}

//编辑
function editDataRole(obj) {
    var roleId = $(obj).parents("tr").attr("getId");
    var roleName = $(obj).parents("tr").attr("name");
    mccms.ajax({
        url: "/role/getRole/" + roleId, //需要添加参数，看接口需要
        method: "GET",
        cache: false,
        success: function (json) {
            var list = [];
            for (var i = 0; i < json.result.permissions.length; i++) {
                list.push(json.result.permissions[i].id);
            }
            editDataRoleAll(list, json, roleId, roleName);
        }
    })
}

function editDataRoleAll(list, da, roleId, roleName, check) {
    //给栏目表录入数据
    mccms.ajax({
        url: "/permission/getPermissionAll",
        method: "GET",
        success: function (json) {
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navEdit",
                container: $("#pathContainer")
            });

            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getEditDataRole",
                container: $("#onClickDataTable"),
                data: da
            });
            for (var i = 0; i < json.result.menu.length; i++) {
                for (var j = 0; j < list.length; j++) {
                    if (json.result.menu[i].id == list[j]) {
                        json.result.menu[i].checked = true;
                    }
                }
            }
            for (var i = 0; i < json.result.front.length; i++) {
                for (var j = 0; j < list.length; j++) {
                    if (json.result.front[i].id == list[j]) {
                        json.result.front[i].checked = true;
                    }
                }
            }
            for (var i = 0; i < json.result.opt.length; i++) {
                for (var j = 0; j < list.length; j++) {
                    if (json.result.opt[i].id == list[j]) {
                        json.result.opt[i].checked = true;
                    }
                }
            }
            if (check) {
                $('.save-btn').remove();
                $('.c-primary').text('查看')
            }
            $("#roleManagement").hide();
            $("#onClickDataTable").show();
            $('.btn_add').hide();

            var setting = {
                check: {
                    enable: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: zTreeOnClick
                }
            };

            json.result.menu[json.result.menu.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                "checked": true,
                open: true
            };
            json.result.front[json.result.front.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                "checked": true,
                open: true
            };
            $.fn.zTree.init($("#roleMenuTree"), setting, json.result.menu.reverse());
            $.fn.zTree.init($("#roleFrontTree"), setting, json.result.front.reverse());

            var data = '';
            for (var i = 0; i < json.result.opt.length; i++) {
                if (json.result.opt[i].checked) {
                    data += '<div class="text-l check-box"><input type="checkbox" checked="checked" roleId="' + json.result.opt[i].id + '" id="checkbox-' + i + '"><label for="checkbox-' + i + '">' + json.result.opt[i].name + '</label></div>'
                } else {
                    data += '<div class="text-l check-box"><input type="checkbox" roleId="' + json.result.opt[i].id + '" id="checkbox-' + i + '"><label for="checkbox-' + i + '">' + json.result.opt[i].name + '</label></div>'
                }
            }
            $("#roleOptTree").html(data);
            $("#roleId").attr({
                "roleId": roleId,
                "roleName": roleName
            })

        }
    })
}

//编辑
function postRoleEditData() {
    var list = [];
    var treeFront = $.fn.zTree.getZTreeObj("roleFrontTree");
    var nodesFront = treeFront.getCheckedNodes(true);
    var treeMenu = $.fn.zTree.getZTreeObj("roleMenuTree");
    var nodesMenu = treeMenu.getCheckedNodes(true);

    for (var i = 0; i < nodesFront.length; i++) {
        list.push(nodesFront[i].id); //获取每个节点的id
    }
    for (var i = 0; i < nodesMenu.length; i++) {
        list.push(nodesMenu[i].id); //获取每个节点的id
    }


    $("#roleOptTree input").each(function () {
        if ($(this).is(':checked')) {
            list.push($(this).attr("roleid"));
        }
    })
    mccms.ajax({
        url: "/role/updateRole",
        method: "POST",
        data: {
            "id": $("#roleId").attr("roleId"),
            "name": $("#roleDescription").val() /*$("#roleId").attr("rolename")*/,
            "status": $('#onClickDataTable .selectVal').val(),
            "description": $("#roleDescription").val(),
            "permissionss": list.toString()
        },
        success: function (json) {
            roleManagement()
            navMenu()
        }
    })
}

//新增
function roleNewData() {
    var roleId = $("#ColumnTableData tr:first").attr("getId");
    var roleName = $("#ColumnTableData tr:first").attr("name");
    mccms.ajax({
        url: "/permission/getPermissionAll",
        method: "GET",
        success: function (json) {
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navAdd",
                container: $("#pathContainer")
            });

            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getNewDataRole",
                container: $("#onClickDataTable"),
                data: json
            });

            $("#roleManagement").hide();
            $("#onClickDataTable").show();
            $('.btn_add').hide();

            var setting = {
                check: {
                    enable: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: zTreeOnClick
                }
            };

            json.result.menu[json.result.menu.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                open: true
            };
            json.result.front[json.result.front.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                open: true
            };
            $.fn.zTree.init($("#roleMenuTree"), setting, json.result.menu.reverse());
            $.fn.zTree.init($("#roleFrontTree"), setting, json.result.front.reverse());

            var data = '';
            for (var i = 0; i < json.result.opt.length; i++) {
                data += '<div class="text-l check-box"><input type="checkbox" roleId="' + json.result.opt[i].id + '" id="checkbox-' + i + '"><label for="checkbox-' + i + '">' + json.result.opt[i].name + '</label></div>'
            }
            $("#roleOptTree").html(data);
            $("#roleId").attr({
                "roleId": roleId,
                "roleName": roleName
            })
        }
    })
}

//保存
function postRoleNewData() {
    var list = [];
    var treeFront = $.fn.zTree.getZTreeObj("roleFrontTree");
    var treeFrontChecked = treeFront.getCheckedNodes(true); //被选中的节点
    var nodesFront = treeFront.transformToArray(treeFront.getCheckedNodes(true));
    var treeMenu = $.fn.zTree.getZTreeObj("roleMenuTree");
    var treeMenuChecked = treeMenu.getCheckedNodes(true); //被选中的节点
    var nodesMenu = treeMenu.transformToArray(treeMenu.getCheckedNodes(true));
    var listChecked = [];
    /*
    for(var i=0;i<nodesFront.length;i++){
        list.push(nodesFront[i].id); //获取每个节点的id
    }
    for(var i=0;i<nodesMenu.length;i++){
        list.push(nodesMenu[i].id); //获取每个节点的id
    }*/

    for (var i = 0; i < treeFrontChecked.length; i++) {
        listChecked.push(treeFrontChecked[i].id); //获取每个被选中节点的id
    }
    for (var i = 0; i < treeMenuChecked.length; i++) {
        listChecked.push(treeMenuChecked[i].id); //获取每个被选中节点的id
    }
    if ($("#roleDescription").val() == "") {
        layer.msg('角色名称不能为空')
        return false;
    }
    mccms.ajax({
        url: "/role/addRole",
        data: {
            "name": $("#roleDescription").val(),
            "status": $('#onClickDataTable .selectVal').val(),
            "description": $("#roleDescription").val(),
            "permissionss": listChecked.toString()
        },
        success: function (json) {
            roleManagement()
        }
    })
}

//删除
function delRoleMode(obj) {
    $("#myModal").attr("getId", $(obj).parents("tr").attr("getid"))
}

function postRoleDelData() {
    mccms.ajax({
        url: "/role/delRole/" + $("#myModal").attr("getId"),
        data: {
            "_method": "delete"
        },
        success: function (json) {
            layer.msg(json.message)
            roleManagement();
            $("#myModal .close").click();
        }
    })
}

/*--权限管理--*/
//列表
var id;

function permissionManage() {
    //给栏目表录入数据
    mccms.ajax({
        url: "/permission/getPermissionAll",
        method: "GET",
        success: function (json) {
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navMain",
                container: $("#pathContainer")
            });

            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getColumnTableData",
                container: $("#ColumnTableData"),
                data: json
            });

            $("#permissionManage").show();
            $("#onClickDataTable").hide();
            $('.btn_add').show();

            var setting = {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id"
                    },
                },
                callback: {
                    onClick: zTreeOnClick
                }
            };

            json.result.menu[json.result.menu.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                open: true
            };
            json.result.front[json.result.front.length] = {
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
                open: true
            };
            $.fn.zTree.init($("#treeMenu"), setting, json.result.menu.reverse());
            $.fn.zTree.init($("#treeFront"), setting, json.result.front.reverse());

        }
    })
}

//新增
function permissionNewData(obj) { //新增数据
    $(".treeFunction").remove();
    mccms.getHbs({ //将数据打包到模版丢进容器
        local: true,
        hbsName: "navNewData",
        container: $("#pathContainer")
    });
    mccms.getHbs({ //将数据打包到模版丢进容器
        local: true,
        hbsName: "getNewData",
        container: $("#onClickDataTable"),
    });

    $("#parentsZTree .modal-body .modal-treeMenu").html(treeMenu);
    $("#parentsZTree .modal-body .modal-treeFront").html(treeFront);

    $("#permissionManage").hide();
    $("#onClickDataTable").show();
    $('.btn_add').hide();
}

function newChooseTree(obj) {
    if ($("#select option:selected").val() == 0) {
        $("#parentsZTree .modal-body .modal-treeMenu").show();
        $("#parentsZTree .modal-body .modal-treeFront").hide();
    } else if ($("#select option:selected").val() == 1) {
        $("#parentsZTree .modal-body .modal-treeMenu").hide();
        $("#parentsZTree .modal-body .modal-treeFront").show();
    }
}

function postNewPermissionData() {
    if ($("#sureParents").val() == "") {
        layer.msg("请先选择-父级权限")
    } else {
        mccms.ajax({
            url: "/permission/addPermission",
            data: {
                name: $("#permissionName").val(),
                description: $("#permissionDescription").val(),
                permissionId: id,
                uri: $("#permissionUri").val(),
                permissionType: $("#onClickDataTable #select option:selected").val()
            },
            success: function (json) {
                layer.msg(json.message);
                permissionManage();
            }
        })
    }
}

//编辑
function getEditPermissionData(obj) {
    var parText = $(obj).parents("ul").prev().find("span:eq(1)").text();
    mccms.ajax({
        url: "/permission/getPermission/" + id,
        method: "GET",
        success: function (json) {
            $(".treeFunction").remove();
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navEdit",
                container: $("#pathContainer")
            });
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getEditData",
                container: $("#onClickDataTable"),
                data: json
            });
            $("#permFirstTr").attr("nodeId", id);
            id = json.result.permissionId;
            $("#parPermission").val(parText);
            $("#select option:eq(" + json.result.permissionType + ")").attr("selected", "selected");

            $("#parentsZTree .modal-body .modal-treeMenu").html(treeMenu);
            $("#parentsZTree .modal-body .modal-treeFront").html(treeFront);

            $("#permissionManage").hide();
            $("#onClickDataTable").show();
            $('.btn_add').hide();
        }
    })
}

function postEditPermissionData() {
    mccms.ajax({
        url: "/permission/updatePermission",
        data: {
            id: $("#permFirstTr").attr("nodeId"),
            name: $("#permissionName").val(),
            description: $("#permissionDescription").val(),
            permissionId: id,
            uri: $("#permissionUri").val(),
            permissionType: $("#onClickDataTable #select option:selected").val()
        },
        success: function (json) {
            layer.msg(json.message);
            permissionManage();
        }
    })
}

//删除
function postDelPermissionData() {
    mccms.ajax({
        url: "/permission/delPermission/" + id,
        data: {
            "_method": "delete"
        },
        success: function (json) {
            layer.msg(json.message);
            permissionManage();
            $(".close").click();
        }
    })
}

function zTreeOnClick(event, treeId, treeNode) {
    id = treeNode.id;
};

function dblClickExpand(treeId, treeNode) {
    return treeNode.level > 0;
}

$(function () {
    //zTree树节点点击时显示编辑，删除
    $("#mainContainer").on("click", "#permissionManage .treeTip a", function (event) {
        $(".treeFunction").remove();
        var title = this.getAttribute('title');
        if (title != "MCCMS") {
            var a_title = $(this).parent().parent().prev().attr('title')
            if (a_title != "贫困户管理") { //权限控制，贫困户管理模块下的内容不可编辑或者删除操作
                var html = "<div class='treeFunction'><span class='treeEdit' onClick='getEditPermissionData(this)'>编辑</span><span class='treeDel' data-toggle='modal' href='#myModal' onclick='modalUser(this)'>删除</span></div>"
                $(this).append(html)
            }

        }
    });
    //权限，当权限类型选为功能时，隐藏父级权限选择
    $("#mainContainer").on("change", "#onClickDataTable #select", function (event) {
        if ($(this).val() == 2) {
            $("#permFirstTr").hide();
        } else {
            $("#permFirstTr").show();
        }
    });
});

//公用方法
function sureParents(obj) {
    var text = $("#parentsZTree .curSelectedNode span:eq(1)").text();
    $("#sureParents").val(text);
    $(".modal-header a").click();
}

/*alex end*/
function columnEdit() {
    var nav = $('#pathContainer.c-primary'),
        main = $('#columnNewTable'),
        columnId = mccms.getHash('columnId') || 0,
        form = $('#columnNewForm'),
        id = mccms.getHash('id'),
        setHbs = function (data) { //填充表单到页面
            var txt = id ? '编辑' : false,
                edit = data ? data.result.content : '',
                val = data ? data.result.template : '',
                data = data || {'result': {"parent": columnId}};

            txt && $('.c-primary').html(txt);
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "columnNewMsg",
                container: $("#columnNewTable"),
                data: data.result,
                callback: function () {
                    form.mcFormValide();
                    //实例化编辑器
                    //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
                    var editor = new UE.ui.Editor();
                    editor.render("uEdit");
                    settemplate(val);
                    $('#columnSub').on('click', subColumn);
                }
            });
        },
        setColumn = function (id) { //获取数据,填充到页面
            mccms.ajax({
                "url": '/column/getColumnById/' + id,
                "method": "GET",
                "success": function (data) {
                    setHbs(data);
                }
            })
        },
        settemplate = function (val) { //异步获取模板数据填充到表单
            var val = val || '';

            mccms.ajax({
                "url": "/column/getColumnTemplate",
                "method": "GET",
                "success": function (json) {
                    mccms.getHbs({ //将数据打包到模版丢进容器
                        local: true,
                        hbsName: "options",
                        container: $("#template"),
                        data: json,
                        callback: function () {
                            val && $("#template").val(val)
                        }
                    });
                }
            })
        },
        /*
         *ele 装载树的容器元素
         */
        columnTree = function (ele) { //初始化zTree
            var setting = { //zTree 配置
                    "view": {
                        dblClickExpand: function (treeId, treeNode) { //双击展开可展开节点
                            return treeNode.level > 0
                        }
                    },
                    "callback": {
                        "onClick": function (event, treeId, treeNode) { //单击回调
                            $('#parentName').val(treeNode.description);
                            $('#parentId').val(treeNode.id);
                            $("#parentsZTree").modal("hide");
                        }
                    },
                    "data": {
                        "key": {
                            "name": "description" //显示名称的key
                        },
                        "simpleData": {
                            "enable": true, //是否启用简单数据模式
                            "idKey": "id",
                            "pIdKey": "permissionId", //父级id的key            
                            "rootPId": 0
                        }
                    }
                },
                zNodes = [{ //zTree data
                    "id": 0,
                    "description": "MCCMS",
                    "open": true
                }];
            mccms.ajax({ //获取ztree数据
                "cache": false,
                "url": "/column/getColumnsInfo",
                "method": "GET",
                "success": function (data) {
                    /*data.result[0][0] 栏目id
                     *data.result[0][1] 栏目父级id
                     *data.result[0][2] 栏目名称
                     */
                    for (var i = 0; i < data.result.length; i++) {
                        zNodes.push({
                            "id": data.result[i][0],
                            "permissionId": data.result[i][1],
                            "description": data.result[i][2],
                            "opend": data.result[i][0] == columnId ? true : false
                        })
                    }
                    zNodes[columnId]
                    // 生成zTree
                    var tree = $.fn.zTree.init(ele, setting, zNodes);
                    var node = tree.getNodeByParam("id", columnId, null); //获取父级元素
                    tree.selectNode(node); // 选中
                    $('#parentName').val(node.description); //填充表单数据
                }
            })
        },
        subColumn = function () { //表单提交
            form.valid() ?
                mccms.ajax({
                    "url": id ? "/column/editColumn" : "/column/newColumn",
                    "data": $('#columnNewForm').serialize(),
                    "success": function () {
                        mccms.goTo('columnMng', 'columnMng', {'columnId': columnId});
                    }
                }) :
                $('.error-lab').eq(0).focus()
        };
    if (id) {
        setColumn(id)
    } else {
        setHbs()
    }
    ;
    columnTree($('#columnTree'));
}

/*栏目信息*/
function columnMng() {
    var columnId = mccms.getHash('columnId') || 0, //当前栏目id
        // add = mccms.getHash('add') ? true : false,//是否新增
        // edit = mccms.getHash('edit') ? true : false,//是否是列表
        listCotainer = $('#tbody'), //列表容器
        // formCotainer = $('#columnNewForm'),//表单容器
        /*
         *ele 装载树的容器元素
         */
        columnTree = function (ele) { //初始化zTree
            var setting = { //zTree 配置
                    "view": {
                        dblClickExpand: function (treeId, treeNode) { //双击展开可展开节点
                            return treeNode.level > 0
                        }
                    },
                    "callback": {
                        "onClick": function (event, treeId, treeNode) { //单击回调
                            if (treeNode.isParent) { //有子级跳该栏目的列表
                                refreshList(1, treeNode.id)
                            } else { //无子级跳编辑栏目
                                mccms.goTo('columnMng', 'columnEdit', {'columnId': columnId, 'id': treeNode.id})
                            }
                            ;
                        }
                    },
                    "data": {
                        "key": {
                            "name": "description" //显示名称的key
                        },
                        "simpleData": {
                            "enable": true, //是否启用简单数据模式
                            "idKey": "id",
                            "pIdKey": "permissionId", //父级id的key            
                            "rootPId": 0
                        }
                    }
                },
                zNodes = [{ //zTree data
                    "id": 0,
                    "description": "MCCMS",
                    "open": true
                }];
            mccms.ajax({ //获取ztree数据
                "cache": false,
                "url": "/column/getColumnsInfo",
                "method": "GET",
                "success": function (data) {
                    /*data.result[0][0] 栏目id
                     *data.result[0][1] 栏目父级id
                     *data.result[0][2] 栏目名称
                     */
                    for (var i = 0; i < data.result.length; i++) {
                        zNodes.push({
                            "id": data.result[i][0],
                            "permissionId": data.result[i][1],
                            "description": data.result[i][2],
                            "opend": data.result[i][0] == columnId ? true : false
                        })
                    }
                    // 生成zTree
                    $.fn.zTree.init(ele, setting, zNodes);
                }
            })
        },
        refreshList = function (pageNo, id) { //刷新列表
            columnId = id || columnId;
            var pageNo = pageNo || mccms.getHash('pageNo') || mccms.stepCache.pageNo || 1;
            mccms.addHash('columnId', columnId);
            mccms.ajax({
                "url": "/column/getColumnsSubList/" + columnId,
                "cache": false,
                "method": "GET",
                "data": {
                    pageNo: pageNo,
                    pageSize: 8
                },
                success: function (data) {
                    mccms.getHbs({ //将数据打包到模版丢进容器
                        "local": true,
                        "hbsName": "columnList",
                        "container": listCotainer,
                        "data": data.result
                    });
                    mccms.pageHtml(data, refreshList); //生成分页
                }
            })
        };
    // 页面初始化
    columnTree($('#columnTree'));
    refreshList();
    // 事件绑定
    $('.add_btn').on('click', function () { //添加栏目
        mccms.goTo('columnMng', 'columnEdit', {'columnId': columnId})
    })
    $('.expand_on').on('click', function () { //展开树
        var tree = $.fn.zTree.getZTreeObj('columnTree');
        tree.expandAll(true);
    })
    $('.expand_off').on('click', function () { //收起树
        var tree = $.fn.zTree.getZTreeObj('columnTree');
        tree.expandAll(false);
    })
    listCotainer.on('click', '.edit_btn', function () {
        // 编辑
        var that = $(this),
            id = that.parents('td').attr('data-id');
        mccms.goTo('columnMng', 'columnEdit', {'columnId': columnId, 'id': id})
    })
    listCotainer.on('click', '.del_btn', function () { // 删除栏目
        var that = $(this),
            name = that.parents('td').attr('data-name'),
            id = that.parents('td').attr('data-id');
        mccms.operation({
            "name": '删除栏目"' + name + '"',
            "method": "DELETE",
            "sub": true,
            "url": "/column/deleteColumn/" + id,
            "fn": refreshList
        })
    })
}

/*--栏目配置-模板类型管理--*/

//列表
function templateManage() {
    //给栏目表录入数据
    mccms.ajax({
        url: "/column/getColumnTemplate",
        method: "GET",
        success: function (json) {
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navMain",
                container: $("#pathContainer")
            });
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "getColumnTableData",
                container: $("#ColumnTableData"),
                data: json
            });
            // mccms.pageHtml(json);        //生成分页
            $("#templateManage").show();
            $("#onClickDataTable").hide();
        }
    })
}

function columnTypeEdit() {
    var form = $('#columnTypeEditForm'),
        id = mccms.getHash('id'),
        setForm = function (data) {
            var txt = id ? '编辑' : false;

            txt && $('.c-primary').html(txt);
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "columnTypeEditMsg",
                container: $('#columnTable'),
                data: data || {},
                callback: function () {
                    form.mcFormValide();
                }
            })
        },
        setDataForm = function (id) {
            mccms.ajax({
                "url": '/column/getColumnTemplateById/' + id,
                "method": "GET",
                "success": function (data) {
                    setForm(data.result);
                }
            })
        },
        submitForm = function () { //表单提交
            form.valid() ?
                mccms.ajax({
                    "url": id ? "/column/editColumnTemplate" : "/column/newColumnTemplate",
                    "data": form.serialize(),
                    "success": function () {
                        mccms.goBack();
                    }
                }) :
                $('.error-lab').eq(0).focus()
        };
    // 页面初始化
    id
        ?
        setDataForm(id) :
        setForm()
    // 事件绑定
    form.on('change', '#templateType', function () {
        $(this).val() === 'other' ?
            $('.other').removeClass('hidden').find('input').prop('disabled', false) :
            $('.other').addClass('hidden').find('input').prop('disabled', true)
    })
    form.on('click', '.btn_sub', function () {
        submitForm()
    })
}

/*--模板类型管理--*/
function column_typeMng() {
    var main = $('#columnTypeManage'),
        nav = 'column_typeMng',
        stepEdit = 'column_typeEdit',
        refreshList = function (pageNo) { //给栏目表录入数据
            var pageNo = pageNo || 0;
            mccms.ajax({
                url: "/column/getColumnTemplate",
                method: "GET",
                success: function (data) {
                    mccms.getHbs({ //将数据打包到模版丢进容器
                        local: true,
                        hbsName: "columnTypeList",
                        container: $("#tbody"),
                        data: data
                    });
                    mccms.pageHtml(data, refreshList); //生成分页
                }
            })
        };
    // 初始化页面
    refreshList()
    // 绑定事件
    main.on('click', '.btn_add', function () {
        mccms.goTo(nav, stepEdit)
    })
    main.on('click', '.btn_edit', function () {
        var that = $(this),
            id = that.parents('td').attr('data-id');
        mccms.goTo(nav, stepEdit, {"id": id});
    })
    main.on('click', '.btn_del', function () {
        var that = $(this),
            name = that.parents('td').attr('data-name'),
            id = that.parents('td').attr('data-id');
        mccms.operation({
            "name": '删除栏目"' + name + '"',
            "method": "DELETE",
            "sub": true,
            "url": "/column/deleteColumnTemplate/" + id,
            "fn": refreshList
        })
    })
}

/*--MCGT START--*/
function Mcgt() {
    $('#subForm').mcFormValide();
    $('#fieldForm').mcFormValide();
    $('.field-sub').on('click', function (event) { //提交
        if (!$('#fieldForm').valid()) {
            return;
        }
        if ($('#field-type').val() == 'varchar' && $('#field-length').val() == '') {
            layer.msg('必须为varchar字段设置长度！')
            return;
        }

        var text = "",
            contain = $("#fieldTr .addfield"),
            ele = $('#fieldTr .input-text'),
            index = $(this).attr('data-index');

        $(".input-text", "#myModal").each(function () {
            text += ($(this).val() || "") + "-"
        });
        index ? ele.eq(index).val(text) : $("#addfield").before('<p><input data-toggle="modal" href="#myModal" type="text" class="input-text input-col-3 mb-10 bgTextColoe" value="' + text + '" readonly="readonly"><input class="del-field btn btn-danger size-MINI radius ml-10 mb-10" type="button" value="删除"></p>');
        $("#myModal .close").click();
        $(".field input").val("");
    });
    $('#fieldTr').on('click', '.input-text', function (event) { //字段编辑
        var that = $(this),
            index = $('#fieldTr .input-text').index(that),
            text = that.val().split("-"),
            ele = $('#myModal .input-text');

        for (i = 0; i < text.length; i++) {
            ele.eq(i).val(text[i]);
        }
        $('.field-sub').attr('data-index', index);
    });
    $('#fieldTr').on('click', '.del-field', function (event) { //字段删除
        var that = $(this);

        that.parents('p').remove();
    });
    $('#addfield').on('click', function (event) { //新增字段
        $(".field input").val("");
        $('.field-sub').removeAttr('data-index');
    });
    $('#mcgtSubmitBtn').on('click', function () { //表单提交
        if (!$('#subForm').valid()) {
            return;
        }
        if ($('#fieldTr .input-text').length < 1) {
            layer.msg('至少需要添加一个字段!');
            return;
        }
        var data0 = {};
        for (var i = 0, j = 0; i < $("#fieldTr input[type='text']").length; i++) {
            var eles = $("#fieldTr input[type='text']"),
                ele = eles.eq(i),
                text = ele.val(),
                type = ele.attr('type');
            if (type == 'text' && text) {
                text = text.split("-");
                data0['mcColumns[' + j + '].name'] = text[0];
                data0['mcColumns[' + j + '].type'] = text[1];
                data0['mcColumns[' + j + '].length'] = text[2];
                data0['mcColumns[' + j + '].notNull'] = text[3];
                data0['mcColumns[' + j + '].defaultValue'] = text[4];
                data0['mcColumns[' + j + '].comment'] = text[5];
                j++;
            }
        }
        var projectRootPathVal = $("#projectRootPathInput").val();
        data0['projectRootPath'] = /\\$/.test(projectRootPathVal) ? projectRootPathVal : projectRootPathVal + "\\";
        data0['moduleName'] = $("#mcgtFieldNameDesc").val();
        data0['moduleNameDesc'] = $("#mcgtFieldName").val();
        data0['name'] = $("#mcgtTableName").val();
        data0['comment'] = $("#mcgtTableNameDesc").val();

        mccms.ajax({
            url: "/mcgenerate/generate",
            method: "POST",
            dataType: "json",
            data: data0,
            success: function (json) {
                layer.msg("提交成功");
                location.reload();
            }
        })
    });
}

/*--MCGT END--*/

/* Gary START */

/* Template START */
function Template() {
    var pathContainerEle = $("#pathContainer");
    var listContainerEle = $("#listContainer");
    var operationContainerEle = $("#operationContainer");

    mccms.getHbs({
        local: true,
        hbsName: "pathMain",
        container: pathContainerEle
    });

    getListData();

    // 当前位置 新增、返回按钮
    pathContainerEle.on("click", ".path-btn", function () {
        var self = $(this);

        // 新增
        if (self.attr("operation") == "new") {
            // 更新当前位置
            mccms.getHbs({
                local: true,
                hbsName: "pathNew",
                container: pathContainerEle
            });
            mccms.getHbs({
                local: true,
                hbsName: "newTemplate",
                container: operationContainerEle
            });

            listContainerEle.hide();
            operationContainerEle.show();
        }
        // 返回
        else if (self.attr("operation") == "back") {
            backToList();
        }
    });

    // 列表 查看/编辑按钮
    listContainerEle.on("click", ".operation-btn", function () {
        var self = $(this),
            geturl = $('nav').attr('data-get'),
            id = self.parents('td').attr('data-id');
        var self = $(this),
            geturl = $('nav').attr('data-get'),
            delurl = $('nav').attr('data-del'),
            id = self.parents('td').attr('data-id');
        if (self.attr("operation") == "del") {
            layer.confirm('确定删除？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    mccms.ajax({
                        "url": delurl,
                        "data": {
                            "id": id
                        },
                        "success": function () {
                            layer.msg('删除成功');
                            getListData();
                        }
                    })
                }
                /*, function(){
                                  layer.msg('也可以这样', {
                                    time: 20000, //20s后自动关闭
                                    btn: ['明白了', '知道了']
                                  });
                                }*/
            );
        } else {
            mccms.ajax({
                "url": geturl + '/' + id,
                "method": "GET",
                "success": function (data) {
                    // 查看
                    if (self.attr("operation") == "check") {
                        mccms.getHbs({
                            local: true,
                            hbsName: "pathCheck",
                            container: pathContainerEle
                        });
                        mccms.getHbs({
                            local: true,
                            hbsName: "editTemplate",
                            container: operationContainerEle,
                            data: data.result,
                            callback: function () {
                                $('.edit-cotent').hide();
                            }
                        });

                        listContainerEle.hide();
                        operationContainerEle.show();
                    }

                    if (self.attr("operation") == "edit") {
                        mccms.getHbs({
                            local: true,
                            hbsName: "navEdit",
                            container: pathContainerEle
                        });
                        mccms.getHbs({
                            local: true,
                            hbsName: "editTemplate",
                            container: operationContainerEle,
                            data: data.result,
                            callback: function () {
                                $('.edit-cotent').show();
                            }
                        });

                        listContainerEle.hide();
                        operationContainerEle.show();
                    }
                }
            })
        }
    });

    // 新增/查看/修改提交按钮
    operationContainerEle.on("click", ".operation-submit-btn", function () {
        var self = $(this),
            addurl = $('nav').attr('data-add'),
            seturl = $('nav').attr('data-update');
        // 新增提交
        if (self.attr("operation") == "new") {
            mccms.ajax({
                url: addurl, //需要添加参数，看接口需要
                data: $("#newForm").serialize(),
                success: function (json) {
                    getListData();
                    backToList();
                }
            })
        }

        if (self.attr("operation") == "edit") {
            mccms.ajax({
                url: seturl, //需要添加参数，看接口需要
                data: $("#newForm").serialize(),
                success: function (json) {
                    getListData();
                    backToList();
                }
            })
        }
    });
}

// 取列表数据，显示列表
function getListData(pageNo) {
    var url = $('nav').attr('data-list'),
        pageNo = pageNo || 1;
    mccms.ajax({
        url: url,
        method: "GET",
        data: {
            "pageNo": pageNo,
            "pageSize": 5
        },
        success: function (data) {
            mccms.getHbs({
                local: true,
                hbsName: "listTemplate",
                container: $("#listContentContainer"),
                data: data
            });

            mccms.pageHtml(data, getListData); //生成分页

            var tableMaxHeightELe = $('.table-maxHeight')[0];
            var scrollbarWidth = tableMaxHeightELe.offsetWidth - tableMaxHeightELe.scrollWidth;
            $("table:eq(0)").css("paddingRight", scrollbarWidth); //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    });
}

function backToList() {
    mccms.getHbs({
        local: true,
        hbsName: "pathMain",
        container: $("#pathContainer")
    });

    $("#listContainer").show();
    $("#operationContainer").hide();
}

/* Template END */

/* Gary END */
function mcgtNew() {
    var projectEle = $('#projectRootPathInput'),
        reg = new RegExp('\\.sql$', 'i'),
        newfile = function (ele) {
            if (!reg.test(this.value)) {
                layer.msg("请选择标准的MySQL,sql文件");
                $('.file-td').html('<input type="file" id="file" id="sqlFile" name="file">')
            }
        };
    $('#file').on('change', newfile);
    $('#mcgtSubmitBtn').on('click', function () { //表单提交
        var projectVal = projectEle.val(),
            fileVal = $('#file').val();
        if (projectVal === '') {
            layer.msg("请填写项目路径");
        } else if (fileVal === '') {
            layer.msg("请选择标准的MySQL,sql文件");
        } else {
            mccms.upload({
                "url": "/mcgenerate/generates",
                "iptid": "file",
                "reg": new RegExp('\\.sql$', 'i'),
                "type": "sql文件",
                "data": {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'projectRootPath': projectVal
                },
                success: function (json) {
                    layer.msg("提交成功");
                }
            })
        }
    });
}

/*-- nav --*/
function navMenu() {
    mccms.ajax({
        url: "/permission/menu",
        method: "GET",
        cache: false,
        success: function (json) {
            var data = [];
            var temp = [];
            var num = 0;
            var logo = ["Hui-iconfont-manage", "Hui-iconfont-user-zhanzhang", "Hui-iconfont-middle", "Hui-iconfont-hetong", "Hui-iconfont-log", "Hui-iconfont-moban", "Hui-iconfont-search2", "Hui-iconfont-shujutongji"]
            for (var i in json.result) {
                if (json.result[i].permissionId == 0) {
                    json.result[i].child = [];
                    /*json.result[i].logo = mccms.styleIcon[json.result[i].description];*/
                    json.result[i].logo = logo[num]
                    num++;
                    data.push(json.result[i]);
                } else {
                    temp.push(json.result[i])
                }
            }
            for (var j in temp) {
                for (var a in data) {
                    if (temp[j].permissionId == data[a].id) {
                        data[a].child.push(temp[j])
                    }
                }
            }
            var json = {};

            json.data = data;
            mccms.getHbs({ //将数据打包到模版丢进容器
                local: true,
                hbsName: "navMenu",
                container: $("#navContainer"),
                data: json,
                callback: function () {
                    $.Huifold("#Huifold .item h4", "#Huifold .item .info", "fast", 1, "click");
                    mccms.refreshShow();
                }
            });
        }
    })
}

/* 修改当前用户密码 */
function passwordEdit() {
    // 变量声明
    var form = $('#passwordManage'),
        id = mccms.getHash('id') || $('#userName').attr('data-id'),
        name = mccms.getHash('name') || $('#userName').html();

    // 流程
    form.mcFormValide(),
        $('.Password-sub').on('click', function (event) {
            var that = $(this),
                valid = form.valid();

            valid
            &&
            mccms.ajax({
                url: "/user/updateUserSafe", //需要添加参数，看接口需要
                method: "POST",
                data: form.serialize() + '&username=' + name + '&id=' + id,
                beforeSend: function () {
                    that.attr('disabled', 'disabled');
                },
                complete: function () {
                    that.removeAttr('disabled');
                },
                success: function () {
                    id == $('#userName').attr('data-id') ?
                        location.replace('logout') :
                        mccms.goBack()
                }
            })
        });
}

/*--基本配置-站点管理--*/
function siteManage() {
    //声明变量
    var bind = function () {
            $('#siteManage').mcFormValide();
            $('.site-btn').on('click', function (event) {
                var ele = $(this);
                $('#siteManage').valid() &&
                mccms.ajax({
                    url: "/site/updateWebSite",
                    method: "POST",
                    data: $('#siteManage').serialize(),
                    "lock": true,
                    "beforeSend": function () {
                        ele && ele.attr('disabled', 'disabled');
                    },
                    "complete": function () {
                        ele && ele.removeAttr('disabled');
                    },
                    success: function () {
                        layer.msg('提交成功', {time: 1500});
                    }
                })
            })
        },
        setform = function (data) {
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "ManageTableMsg",
                "container": $("#ManageTable"),
                "data": data,
                "callback": bind
            });
        };
    //流程
    mccms.ajax({
        cache: false,
        url: "/site/getWebSite",
        method: "GET",
        success: function (data) {
            setform(data.result)
        }
    });
}

/*--用户管理--*/
var levelId = mccms.getHash('levelId'); // 等级ID
var level = mccms.getHash('level'); // 等级level
var areaId = mccms.getHash('areaId'); // 地区ID
var userLevel = $("input[data-userLevel]").attr("data-userLevel"); // 用户等级
function userManage() {
    // 变量声明
    var main = $('#userManage'),
        form = $('#searchForm'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({
                    "url": "/user/finduser",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "userList",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                /*超出省略号 start*/
                                $("#tbody .remarks").each(function () {
                                    if ($(this).text().length > 80) {
                                        var text = $(this).text().substring(0, 20) + "...";
                                        $(this).text(text);
                                    }
                                })
                                /*超出省略号 end*/

                                /*重置密码按钮 start*/
                                if (userLevel != 0) { //用户等级不为系统级,则删除重置密码按钮
                                    $("#tbody .password_btn").remove();
                                }
                                /*重置密码按钮 end*/
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件

                                    for (var i in prevFrom) {
                                        if (i == "cry") {
                                            $('#cry option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-cry").val($(this).attr("data-number")) //乡code值回显
                                                }
                                            })
                                            cryVal = prevFrom[i] //乡赋值，用于分页点击之后回显
                                        } else if (i == 'name') {

                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            $('#name option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-name").val($(this).attr("data-number")) //村code值回显
                                                }
                                            })
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");


                                //乡回显
                                if (cryVal) {
                                    $('#cry').val(cryVal)
                                }

                            }
                        });

                        //点击数据项添加背景色 
                        tdAddBg('tbody')

                        //乡选中加载村数据
                        $("#cry").change(function () {
                            cryId = $(this).find("option:checked").attr("id");
                            cryVal = $(this).find("option:checked").val();
                            $("#h-cry").val($(this).find("option:checked").attr("data-number"))
                            $("#h-name").val("") //清空村值
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": cryId
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="" selected>请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].id + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#name").html(naturalsHtml);
                                }
                            });
                        });
                        //村选中加载村数据

                        $("#name").change(function () {
                            s_name_id = $(this).find("option:checked").attr("data-number"); //村的code值赋予给全部变量s_name_id
                            nameVal = $(this).find("option:checked").val(); //村名
                            $("#h-name").val(s_name_id);
                            $("name").val(nameVal) //村回显

                        });
                    }
                })
            });
        };

    // 流程
    $('.add_btn').on('click', function () { // 新增
        mccms.goTo("user_management", "user_msg");
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parents('td').attr('id');
        mccms.goTo("user_management", "user_msg", {
            "id": id,
            "operated": 1
        });
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $(this).parents('td').attr('id');
        mccms.goTo("user_management", "user_msg", {
            "id": id,
            "operated": 0
        });
    });
    main.on('click', '.password_btn', function () { //重置密码
        var id = $(this).parent('td').attr('id');
        layer.confirm("确定要重置密码吗？", function () {
            mccms.ajax({
                "url": "/user/updatePassword",
                "cache": false,
                "method": "POST",
                "data": {"id": id},
                "success": function (data) {
                    if (data.status == 200) {
                        layer.msg("密码重置成功！")
                    } else if (data.status == 400) {
                        layer.msg("密码重置失败！")
                    }
                }
            })
        })

    });
    main.on('click', '.del_btn', function () { //删除
        var id = $(this).parents('td').attr('id');

        mccms.operation({
            "method": "delete",
            "name": '删除用户',
            "url": "/user/delUser/" + id,
            "sub": true,
            "fn": function () {
                layer.msg("删除成功！")
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true'); // 查询后刷新页面
    });
    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "cry": $('#cry option:selected').val(),
            "name": $('#name option:selected').text(),
            "h-cry": $('#h-cry').val(),
            "h-name": $('#h-name').val(),
            "username": $('#username').val(),
            "realName": $('#realName').val(),
            "mobilePhone": $('#mobilePhone').val(),
            "email": $('#email').val(),
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize);

}

// 用户信息
function userMsgEdit() {
    // 变量声明
    var id = mccms.getHash('id'), //用户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        form = $('#userForm'),
        path = $('.c-primary'),
        setUserToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/user/editUser/" + id,
                "cache": false,
                "method": "GET",
                "data": {
                    pageNo: 1,
                    pageSize: 100
                },
                success: function (data) {
                    var data = data || {
                            result: {},
                            user: {
                                roles: []
                            }
                        },
                        roles = data.result.user.roles;
                    data.result.detail = operated,
                        setForm(data.result, roles.length > 0 ? roles[0].id : 'eva')


                }
            })
        },

        setRoleToForm = function () { //查询所属角色
            mccms.ajax({
                "url": "/role/getRoleAllFilter",
                "cache": false,
                "method": "GET",
                "data": {
                    pageNo: 1,
                    pageSize: 100
                },
                success: function (data) {
                    setForm({"add": 1, "role": data.result})
                    $('input[name="username"]').removeAttr("disabled");
                }
            })
        },
        setForm = function (data, checkedId) { //填充表单
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "userMsg",
                "container": form,
                "data": data,
                "callback": function () {
                    var txt = operated ? '查看用户信息' : '编辑用户信息';
                    if (!checkedId) {
                        $('.radio-box input[type="radio"]').eq(0).iCheck('check')
                    }
                    id && path.html(txt), //修改模块名称
                        $('.radio-box input[type="radio"]').iCheck({
                            checkboxClass: 'icheckbox-blue',
                            radioClass: 'iradio-blue',
                            increaseArea: '20%'
                        }),
                    checkedId !== 'eva' && $('#role' + checkedId).iCheck('check'),
                        form.mcFormValide() //绑定表单验证 
                }
            })
        },
        subMsg = function (ele) { //提交用户数据
            var areaId = mccms.getHash('areaId'); //地区ID
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/user/updateUserInfo" : "/user/addUser",
                data = data + "&userlevelid=" + levelId + "&areaId=" + areaId; //分别 编辑、新增的参数


            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "lock": true,
                "beforeSend": function () {
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": mccms.goTo("user_msg", "user_management")

            })
        };
    // 流程
    $("#goUserMng").on("click", function () { //跳转至用户管理
        mccms.goTo("user_msg", "user_management");
    })

    id ? setUserToForm() : setRoleToForm(),
        form.on('click', '.sub_btn', function () {
            subMsg($(this))
        })
}


/**
 * Created by caiwen on 2017/9/28.
 */

/*--角色管理-等级管理--*/
function roleLevel() {
    // 变量声明
    var main = $('#main'),
        getList = function (pageNo) {
            var pageNo;
            mccms.ajax({
                "url": "/userLevel/getUserLevelAll",
                "cache": false,
                "method": "GET",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": 8
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "userList",
                        "container": $("#tbody"),
                        "data": data
                        // "callback" : function(){}
                    });
                    mccms.pageHtml(data, getList, []);
                }
            })
        };
    // 流程
    main.on('click', '.ensure_btn', function () {
        levelId = $(this).parents('td').attr('levelId'); // 系统级别ID
        var level = $(this).parents('td').attr('level');
        var userLevel = $("input[data-userLevel]").attr("data-userLevel"); // 用户等级
        var id = mccms.getHash('id'); // 当前编辑id
        var operated = mccms.getHash('operated'); // 0表示编辑，1表示查看

        if (userLevel == level) { // 系统级别与选择级别相等，直接跳至新增页面
            mccms.goTo("roleLevel", "user_msg", {
                "levelId": levelId,
                "level": level,
                "areaId": 0,
                "id": id,
                "operated": operated
            });
        } else {
            mccms.goTo("roleLevel", "area", {
                "levelId": levelId,
                "level": level,
                "id": id,
                "operated": operated
            });
        }

    });
    $("#goUserMng").on("click", function () { // 跳转至用户管理
        mccms.goTo("roleLevel", "user_management");
    })

    getList();

}

function area() {
    // 变量声明
    var main = $('#main'),
        getList = function (pageNo, id) {
            var pageNo = pageNo || mccms.getHash('pageNo') ||
                mccms.stepCache.pageNo;
            var level = mccms.getHash('level');
            mccms.ajax({
                "url": "/area/getAllAreas",
                "cache": false,
                "method": "POST",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": 8,
                    "level": level
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "userList",
                        "container": $("#tbody"),
                        "data": data
                        // "callback" : function(){}
                    });
                    mccms.pageHtml(data, getList, []);

                }
            })
        };
    // 流程
    main.on('click', '.ensure_btn', function () {
        var areaId = $(this).parents('td').attr('areaId'); // 地区ID取值
        var id = mccms.getHash('id'); // 当前编辑id
        var operated = mccms.getHash('operated'); // 0表示编辑，1表示查看
        mccms.goTo("area", "user_msg", {
            "levelId": levelId,
            "level": level,
            "areaId": areaId,
            "id": id,
            "operated": operated
        }); // 跳至用户新增页面
    });
    $("#goUserMng").on("click", function () { // 跳转至用户管理
        mccms.goTo("area", "user_management");
    })
    getList();
}

/*---------------------非系统菜单-----------------------*/
/**
 * Created by caiwen on 2017/9/29.
 */

/* 必填提示方法 start */
function myRequired(formName, popupName) { //formName表单名字，popupName弹窗名字
    var arr = []; //必填元素的数组
    $("#" + formName + " .mccms-validate-required").each(function () { //遍历必填框
        if ($(this).val() == "") { //为空的必填框
            arr.push($(this))
        }
    });
    if (arr.length == 0) { //全部填写完时，跳出此方法
        return false
    }
    var arrTabConIndex = arr[0].parents(".tabCon").index(".tabCon"); //第一个必填框的tabCon索引值
    $("#" + popupName + " .tabBar span").eq(arrTabConIndex).click(); //对应tabBar加click

}

/* 必填提示方法 end */
/*全选共用方法 start*/
/*function checkAll() {
    $("#checkAll").on("click", function() {
        var checkboxs = $("input[name='checkbox']");
        if ($(this).is(':checked')) {
            checkboxs.each(function() {
                $(this).prop("checked", true);
            });
        } else {
            checkboxs.each(function() {
                $(this).removeAttr("checked", false);
            });
        }
    })
}*/
/*全选共用方法 end*/

/*弹窗共用方法*/
function popup(title) {
    //弹窗-新增、查看、编辑
    layer.open({
        type: 1,
        area: ['80%', '80%'],
        title: title,
        shade: 0.5,
        moveType: 1,
        shift: 0,
        content: $('#popup')
    })

    /*tab切换JS初始化*/
    // #tab_demo 父级id
    // #tab_demo .tabBar span 控制条
    // #tab_demo .tabCon 内容区
    // click 事件 点击切换，可以换成mousemove 移动鼠标切换
    // 1    默认第2个tab为当前状态（从0开始）
    $.Huitab("#tab .tabBar span", "#popup .tabCon", "currents", "click", "0")
}

/*弹窗共用方法*/
function addPopup(option) {
    //弹窗-新增
    /*扩展 by Jeremy 2017.10.10
     * 可传layer.open方法的对象，用于不同设计稿对弹窗各项配置的要求
     * */
    var defaultOption = {
            type: 1,
            area: ['1220px', '670px'],
            title: '新增',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#addPopup')
        },
        opt = $.extend(defaultOption, option);
    $(".add_btn").on("click", function () {
        layer.open(opt);
    })

    /*tab切换JS初始化*/
    // #tab_demo 父级id
    // #tab_demo .tabBar span 控制条
    // #tab_demo .tabCon 内容区
    // click 事件 点击切换，可以换成mousemove 移动鼠标切换
    // 1    默认第2个tab为当前状态（从0开始）
    $.Huitab("#addTab .tabBar span", "#addPopup .tabCon", "currents", "click", "0")
}

function detailPopup() {
    //弹窗-查看
    $(".detail_btn").on("click", function () {
        layer.open({
            type: 1,
            area: ['80%', '80%'],
            title: '查看更多详情',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#detailPopup')
        })
    })

    $.Huitab("#detailTab .tabBar span", "#detailPopup .tabCon", "currents", "click", "0")
}

function editPopup() {
    //弹窗-编辑
    $(".edit_btn").on("click", function () {
        layer.open({
            type: 1,
            area: ['80%', '80%'],
            title: '编辑',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#editPopup')
        })
    })

    $.Huitab("#editTab .tabBar span", "#editPopup .tabCon", "currents", "click", "0")
}

// 默认地区选中
/*cryVal:系统用户权限的乡值
nameVal:系统用户权限的村值*/
function areaSelected(cryVal, nameVal, checkType, callback) {
    mccms.ajax({
        "url": "/area/findarea",
        "cache": false,
        "method": "POST",
        "data": {
            "fatherId": 3 //3代表魏县的id
        },
        success: function (data) {
            if (checkType == 'true') {

            } else {
                var cryHtml = '<option value="" >请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                }
                $("#cry").html(cryHtml);
            }
            if (s_Level == 1) {
                $("#province").val(s_province);
                $("#h-province").val(s_province_id);
                $("#province").attr("disabled", "disabled");
            }
            if (s_Level == 2) {
                $("#province").val(s_province);
                $("#h-province").val(s_province_id);
                $("#city").val(s_city);
                $("#h-city").val(s_city);
                $("#province").attr("disabled", "disabled");
                $("#city").attr("disabled", "disabled");
            }
            if (s_Level == 3 || s_Level == 4 || s_Level == 5) {
                //页面获取省名称和id
                $("#province").val(s_province);
                $("#h-province").val(s_province_id);
                //页面获取市名称和id
                $("#city").val(s_city);
                $("#h-city").val(s_city);

                //获取县
                $("#cty").val(s_cty);
                $("#h-cty").val(s_cty_id);

                /*$('#h-name').val(s_name_id)*/
                $("#province").attr("disabled", "disabled");
                $("#city").attr("disabled", "disabled");
                $("#cty").attr("disabled", "disabled");
            }
            if (cryVal && !s_cry) { //admin下选择乡镇查询，回显乡值
                /*$("#cry").val(cryVal)*/
                $('#cry option').each(function () {
                    if ($(this).val() == cryVal) {
                        $(this).attr('selected', 'selected')
                    }
                })
            }
            console.log(sessionStorage.getItem('backId'))
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看等返回回显村值
                var prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'))
                cheId;
                console.log(prevFrom)
                $('#cry option').each(function () {
                    if ($(this).val() == prevFrom.cry) {
                        cheId = $(this).attr('id')
                    }
                })

                //根据用户的乡查询所有的村并选中相应值
                mccms.ajax({
                    "url": "/area/findarea",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "fatherId": cheId
                    },
                    success: function (data) {
                        var naturalsHtml = '<option value="" selected>请选择</option>';
                        for (var i = 0; i < data.result.length; i++) {
                            naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                        }
                        $("#name").html(naturalsHtml);
                        $('#name option').each(function () {
                            if ($(this).val() == prevFrom.name) {
                                $(this).attr('selected', 'selected')
                            }
                        })

                    }
                });
            }

            if (cryVal && s_cry) {
                $("#province").val(s_province);
                $("#h-province").val(s_province_id);
                $("#city").val(s_city);
                $("#h-city").val(s_city);
                $("#cty").val(s_cty);
                $("#h-cty").val(s_cty);
                $("#cry").val(cryVal);
                var cheId = $("#cry").find("option:checked").attr("id");
                $("#h-cry").val(s_cry_id);
                $('#cry2').attr('disabled', 'disabled')

                /*$("#h-name").val(s_name_id);*/

                $("#province").attr("disabled", "disabled");
                $("#city").attr("disabled", "disabled");
                $("#cty").attr("disabled", "disabled");
                $("#cry").attr("disabled", "disabled");
                //根据用户的乡查询所有的村并选中相应值
                mccms.ajax({
                    "url": "/area/findarea",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "fatherId": cheId
                    },
                    success: function (data) {
                        var naturalsHtml = '<option value="" selected>请选择</option>';
                        for (var i = 0; i < data.result.length; i++) {
                            naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                        }
                        $("#name").html(naturalsHtml);
                        if (nameVal) {
                            $("#name").val(nameVal); //显示查询的显示值
                            if (s_name) {
                                $("#name").attr("disabled", "disabled");
                            }
                        }

                    }
                });
            }
            if (callback) {
                callback();
            }
        }
    });
}

/**
 * @method [导入上传方法]
 * @method importUpload
 * @date 2017-11-14
 * @author Arthur - caiwen
 * @tips 导入上传方法原理: 分先上传再导入两步骤。
 * @tips 按钮导入功能,直接调用importUpload()方法 就行,包含了上传与导入两步骤
 * @tips getList 刷新页面方法; no 与 size 为方法参数
 */

/* 导入上传方法 */
function importUpload(importAPI, getList, no, size) {
    $('#mainContainer').on('click', '.import_btn', function () {
        var uploadElm = $("#file");
        $("#mainContainer img.loadFile").remove(); //删除多余进度条
        uploadElm.after('<img class="loadFile" style="width: 100px;height: 7px;display:none" src="img/loadFile.gif" alt="正在上传">');
        var file = document.getElementById('file');
        file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值,取消上传之后可再次上传该文件

        $('#mainContainer').off().on('change', '#file', function () {
            /* $("img.loadFile").show();
             $.ajaxFileUpload({
                 url: mccms.domain[0] + '/base/fileUpload', //用于文件上传的服务器端请求地址
                 type: 'post',
                 secureuri: false, //是否需要安全协议，一般设置为false
                 fileElementId: 'file', //文件上传域的IDS
                 dataType: 'json',
                 success: function(data, xhr, jqXHR) //服务器成功响应处理函数
                 {
                     $("img.loadFile").hide();
                     layer.msg("上传文件成功！");
                     //询问是否进行导入
                     layer.confirm('您是否确认导入？', {
                             btn: ['导入', '取消'] //按钮
                         },
                         function() { //确认方法
                             var fileUrl = data.result; //Excel文件路径
                             importFn(fileUrl, importAPI, getList, no, size); //导入方法
                         })
                 },
                 error: function(data, status, e) //服务器响应失败处理函数
                 {
                     alert(e)
                 }
             })*/
            var fileName = document.getElementById('file').value.split('.')[1]; //文件后缀名
            if (fileName != 'xls') { //格式限制
                layer.msg("目前只支持.xls格式的文件")
                return false
            }
            fileUploads(importAPI, getList, no, size);

            /*mccms.upload({
                iptid: 'file',
                url: '/base/fileUpload',
                reg: new RegExp('\\.xls$', 'i'),
                type: "Excel格式(后缀.xls)",
                success: function(data) {
                    layer.msg("上传文件成功！")
                    //询问是否进行导入
                    layer.confirm('您是否确认导入？', {
                            btn: ['导入', '取消'] //按钮
                        },
                        function() { //确认方法
                            var fileUrl = data.result; //Excel文件路径
                            importFn(fileUrl, importAPI, getList, no, size); //导入方法
                        })
                },
                error: function(){
                    alert("错误");
                }

            });*/
        })
    })


}

/*上传方法*/
function fileUploads(importAPI, getList, no, size) {
    $("img.loadFile").show();

    $.ajaxFileUpload({
        url: mccms.domain[0] + '/base/fileUpload', //用于文件上传的服务器端请求地址
        type: 'post',
        secureuri: false, //是否需要安全协议，一般设置为false
        fileElementId: 'file', //文件上传域的IDS
        dataType: 'json',
        success: function (data, xhr, jqXHR) //服务器成功响应处理函数
        {
            $("img.loadFile").hide();
            layer.msg("上传文件成功！");
            //询问是否进行导入
            layer.confirm('您是否确认导入？', {
                    btn: ['导入', '取消'] //按钮
                },
                function () { //确认方法
                    var fileUrl = data.result; //Excel文件路径
                    importFn(fileUrl, importAPI, getList, no, size); //导入方法
                    importUpload(importAPI, getList, no, size)
                },
                function () { //取消方法
                    importUpload(importAPI, getList, no, size)
                })
        },
        error: function (data, status, e) //服务器响应失败处理函数
        {
            alert(e)
        }
    })
}

/* 导入方法 */
function importFn(fileUrl, importAPI, getList, no, size) {
    mccms.ajax({
        "url": importAPI, //导入接口
        "data": {file: fileUrl},
        "lock": true,
        "method": "POST",
        "success": function (data) {
            var status = data.status; //返回转态值
            switch (status) {
                case "200":
                    layer.msg(data.message) //导入成功
                    getList(no, size)
                    /* window.location.reload();*/
                    break;
                case "300":
                    //导入失败提示框
                    layer.open({
                        type: 1,
                        title: "导入失败提示",
                        skin: 'layui-layer-rim', //加上边框
                        area: ['500px', '500px'], //宽高
                        content: data.result, //导入失败提示
                        success: function () {
                            $(".layui-layer-rim .layui-layer-content").css("overflow", "scroll")
                        },
                        cancel: function (index, layero) {
                            // getList(no, size)
                            window.location.reload();
                        }
                    });

                    break;
                default:
                    layer.msg(data.message)
            }

        }
    })
}

/**
 * @method [当前年方法]
 * @method ThisYear
 * @date 2017-11-30
 * @author Arthur - caiwen
 * @tips 年度初始值为当前年
 */
/* 当前年方法 */
var businessAnnual = $("input[name=businessAnnual]").val(); //当前年是否已经备份 false表示没有备份
function ThisYear() {
    $("#year").val(businessAnnual)
}


/**
 * ------------------------------------------------------------------
 * @project [fuping background management system]
 * @module menu function
 * @date 2017-09-28
 * @author Arthur - caiwen
 * ------------------------------------------------------------------
 */

/*--自然村管理--*/
function naturalVillageMng() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        countryName, //村名
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({
                    "url": "/poorVi/queryNaVague",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "List",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == 'cry') {
                                            $('#' + i).val(prevFrom[i]).trigger('change')
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            countryName = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }

                                    /*$('#name').find('option:selected').text(countryName) //回显村名*/
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");

                                //点击数据项添加背景色
                                tdAddBg('tbody')

                                laydate.render({
                                    elem: '#year', //指定元素
                                    type: 'year'
                                })
                                //乡回显
                                if (cryVal) {
                                    $('#cry').val(cryVal)

                                }
                            }
                        });

                    }
                })
            });
        };

    //乡选中加载村数据
    $("#cry").change(function () {
        cryId = $(this).find("option:checked").attr("id");
        cryVal = $(this).find("option:checked").val();
        $("#h-cry").val($(this).find("option:checked").attr("data-number"))
        $("#h-name").val("") //清空村值
        mccms.ajax({
            "url": "/area/findarea",
            "cache": false,
            "method": "POST",
            "data": {
                "fatherId": cryId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                }
                $("#name").html(naturalsHtml);
                if (countryName) {
                    $("#name option").each(function (ele) {
                        if ($(this).text() == countryName) {
                            $(this).attr('selected', 'selected')
                        }

                    })
                }
            }
        });
    });
    //村选中加载村数据
    $("#name").change(function () {
        nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
        s_name_id = $(this).find("option:checked").attr("data-number");
        $("#h-name").val(s_name_id);
    });

    ThisYear(); //备份当前年
    // 流程
    main.on('click', '.add_btn', function () { //新增
        mccms.goTo("naturalVillageMng", "naturalVillageEdit");
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parents('td').attr('id');
        mccms.goTo("naturalVillageMng", "naturalVillageEdit", {"id": id, "operated": 1});
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $(this).parents('td').attr('id');
        mccms.goTo("naturalVillageMng", "naturalVillageEdit", {"id": id, "operated": 0});
    });
    main.on('click', '.del_btn', function () { //删除
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "delete",
            "name": '删除',
            "url": "/poorVi/deletePoorVillages?id=" + id,
            "sub": true,
            "fn": function () {
                /* layer.msg("删除成功！")*/
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')

    });
    main.on('click', '.refresh_btn', function () { //刷新
        getList();
    });
    main.on('click', ".export_btn", function () { //导出功能
        location.href = "poorVi/exportNaVillage?" + $("#searchForm").serialize();
    });

    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "cry": $('#cry').val(),
            "name": $('#name').val(),
            "village": $('#village').val(),
            "groupNumber": $('#groupNumber').val(),
            "contact": $('#contact').val(),
            "fpeople": $('#fpeople').val(),
            "h-cry": $('#h-cry').val(),
            "h-name": $('#h-name').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)

}

/*-- 自然村新增、编辑、查看方法 --*/
function naturalVillageEdit() {
    var id = mccms.getHash('id'), //用户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        form = $('#editForm'),
        path = $('.c-primary'),
        setNoticeToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/poorVi/getPoorVillage?id=" + id,
                "cache": false,
                "method": "POST",
                success: function (data) {
                    var data = data || {
                        result: {}
                    };
                    data.result.detail = operated,
                        setForm(data.result);
                }
            })
        },
        setAddToForm = function () {
            setForm();
            /*定位锚点，点击导航栏跳转到指定位置*/
            /* scrollToBox('nav_item')*/
        },
        setForm = function (data) { //填充表单
            var country = [],
                village = [],
                cryId;
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "editList",
                "container": form,
                "data": data,
                "callback": function () {
                    if (inquire == 1) { //inquire == 1从《账表查询》过来则修改模块名称
                        $("nav .menuLevel1").html("账表查询");
                        $("nav .menuLevel2").html("自然村查询");
                        $("nav .c-primary").html("查看自然村");
                    }

                    var txt = operated ? '查看自然村' : '编辑自然村';
                    id && path.html(txt), //修改模块名称
                        form.mcFormValide() //绑定表单验证

                    if (operated == 1) {
                        $(".keepBtnBox").hide();
                    }

                    /*定位锚点，点击导航栏跳转到指定位置*/
                    scrollToBox('nav_item')
                    /**
                     * 模板加载后，获取到select框的值，给页面加载选中状态
                     *
                     */
                    var countryVal, //定义乡
                        natrueVal, //定义村

                        nature, //定义村属性
                        roadVal, //定义通路
                        electricVal, //定义生产用电
                        lifeVal, //定义生活用电
                        broadbandVal; //定义宽带

                    if (s_cry || s_name) {
                        countryVal = s_cry;
                        natrueVal = s_name;
                    }
                    if (data.cry) {
                        countryVal = data.cry; //获取到乡的值 
                    }
                    if (data.name) {
                        natrueVal = data.name; //获取到自然村的值  
                    }
                    if (data.nature) {
                        nature = data.nature; //获取村属性值 
                    }
                    if (data.road) {
                        roadVal = data.road; //获取通路属性值
                    }
                    if (data.electrics) {
                        electricVal = data.electrics; //获取生产用电属性值
                    }
                    if (data.lifes) {
                        lifeVal = data.lifes; //获取生活用电属性值
                    }
                    if (data.broadbands) {
                        broadbandVal = data.broadbands; //获取宽带属性值
                    }
                    //根据获取的值，将自然村属性selected选中
                    $("#nature option").each(function (i) {
                        if ($(this).val() == nature) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#road option").each(function (i) {
                        if ($(this).val() == roadVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#electric option").each(function (i) {
                        if ($(this).val() == electricVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#life option").each(function (i) {
                        if ($(this).val() == lifeVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#broadband option").each(function (i) {
                        if ($(this).val() == broadbandVal) {
                            $(this).attr("selected", "selected");
                        }
                    });

                    //10-11 wage add 地区三级联动select填充
                    mccms.ajax({
                        "url": "/area/findarea",
                        "cache": false,
                        "method": "POST",
                        "data": {
                            "fatherId": 3 //3代表魏县的id
                        },
                        success: function (data) {

                            var cryHtml = '<option value="" selected>请选择</option>';
                            for (var i = 0; i < data.result.length; i++) {
                                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                            }

                            $("#cry-add").html(cryHtml);

                            //编辑和查看下地区select框的填充
                            if (countryVal) { //乡的值填充
                                $("#cry-add option").each(function (i) {
                                    if ($(this).val() == countryVal) {
                                        $(this).attr("selected", "selected");
                                        $("#editForm #s-cry-add").val($(this).val());
                                        if (s_Level == 4 || s_Level == 5) {
                                            $("#cry-add").attr("disabled", "disabled");
                                        }
                                        cryId = $(this).attr("id"); //获取乡的选中值用来加载村的数据

                                        mccms.ajax({
                                            "url": "/area/findarea",
                                            "cache": false,
                                            "method": "POST",
                                            "data": {
                                                "fatherId": cryId
                                            },
                                            success: function (data) {
                                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                                for (var i = 0; i < data.result.length; i++) {
                                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                                }
                                                $("#natrueName-add").html(naturalsHtml);

                                                if (natrueVal) { //村的值填充
                                                    $("#natrueName-add option").each(function (i) {
                                                        if ($(this).val() == natrueVal) {

                                                            if (s_Level == 4 || s_Level == 5) {
                                                                $("#cry-add").attr("disabled", "disabled");
                                                            }
                                                            $(this).attr("selected", "selected");

                                                            $("#s-natrueName-add").val($(this).val());
                                                            if (s_Level == 5) {
                                                                $("#natrueName-add").attr("disabled", "disabled");
                                                            }
                                                            var natrueNum = $(this).attr("data-number"); //选中村之后，自动填充村编号
                                                            var natureId = $(this).attr("id");
                                                            $("#code").val(natrueNum);
                                                            $("#natureId").val(natureId);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        }


                    });


                    $("#cry-add").change(function () {
                        cryId = $(this).find("option:checked").attr("id");
                        $("#s-cry-add").val($(this).find("option:checked").val());
                        mccms.ajax({
                            "url": "/area/findarea",
                            "cache": false,
                            "method": "POST",
                            "data": {
                                "fatherId": cryId
                            },
                            success: function (data) {
                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                for (var i = 0; i < data.result.length; i++) {
                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                }
                                $("#natrueName-add").html(naturalsHtml);
                            }
                        });

                    });
                    $("#natrueName-add").change(function () {
                        natrueNum = $(this).find("option:checked").attr("data-number"); //选中村之后，自动填充村编号
                        var natureId = $(this).find("option:checked").attr("id");
                        $("#natureId").val(natureId);
                        $("#s-natrueName-add").val($(this).find("option:checked").val());
                        $("#code").val(natrueNum);
                        $("#code").attr("readonly", "readonly");
                    });
                    //10-11 wage add
                }
            })
        },

        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/poorVi/updateNaVillage" : "/poorVi/addNaVillage"; //前者编辑API，后者新增API
            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "lock": true,
                "method": "POST",
                "beforeSend": function () {
                    if (!id) {
                        form
                    }
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": function () {
                    layer.msg("保存成功！");
                    id ? mccms.gobackFromEdit() : mccms.goBack()
                }
            })
        };

    // 流程
    id ? setNoticeToForm() : setAddToForm(),
        form.on('click', '.sub_btn', function () {
            subMsg($(this));
        })

}

/*-- 贫困村管理 --*/
function poorVillageMng() {
    // 变量声明 
    var main = $('#mainList'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        countryName, //村名
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({
                    "url": "/poorVi/queryPoVague",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "List",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom')); //获取保存查询条件

                                    //从编辑、查看页面返回，显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == 'cry') {
                                            $('#' + i).val(prevFrom[i]).trigger('change')
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            countryName = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);
                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记
                                sessionStorage.removeItem("backId");
                                //点击数据项添加背景色 
                                tdAddBg('tbody')

                                /*//乡选中加载村数据
                                $("#cry").change(function() {
                                    cryId = $(this).find("option:checked").attr("id");
                                    cryVal = $(this).find("option:checked").val();
                                    $("#h-cry").val($(this).find("option:checked").attr("data-number"));
                                    $("#h-name").val("") //清空村值
                                    mccms.ajax({
                                        "url": "/area/findarea",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            "fatherId": cryId
                                        },
                                        success: function(data) {
                                            var naturalsHtml = '<option value="" selected>请选择</option>';
                                            for (var i = 0; i < data.result.length; i++) {
                                                naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                            }
                                            $("#name").html(naturalsHtml);
                                            if(countryName){
                                                $('#name option').each(function(index, el) {
                                                    if($(this).text() == countryName){
                                                        $(this).attr('selected','selected')
                                                    }

                                                });
                                            }
                                        }
                                    });
                                });*/
                                //村选中加载村数据
                                $("#name").change(function () {
                                    nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
                                    s_name_id = $(this).find("option:checked").attr("data-number");
                                    $("#h-name").val(s_name_id);
                                });

                                //年度
                                laydate.render({
                                    elem: '#year',
                                    type: 'year'
                                })

                            }
                        })
                    }
                })
            });
        }
    //乡选中加载村数据
    $("#cry").change(function () {
        cryId = $(this).find("option:checked").attr("id");
        cryVal = $(this).find("option:checked").val();
        $("#h-cry").val($(this).find("option:checked").attr("data-number"));
        $("#h-name").val("") //清空村值
        mccms.ajax({
            "url": "/area/findarea",
            "cache": false,
            "method": "POST",
            "data": {
                "fatherId": cryId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                }
                $("#name").html(naturalsHtml);
                if (countryName) {
                    $('#name option').each(function (index, el) {
                        if ($(this).text() == countryName) {
                            $(this).attr('selected', 'selected')
                        }

                    });
                }
            }
        });
    });
    ThisYear(); //当前年
    // 流程
    $('.add_btn').on('click', function () { //新增
        mccms.goTo("poorVillageMng", "poorVillageEdit");
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parents('td').attr('id'); //用户ID
        areaId = $(this).parents('td').attr("areaId"); //地区ID
        mccms.goTo("poorVillageMng", "poorVillageEdit", {"id": id, "operated": 1, "areaId": areaId});
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $(this).parents('td').attr('id'); //用户ID
        areaId = $(this).parents('td').attr("areaId"); //地区ID
        mccms.goTo("poorVillageMng", "poorVillageEdit", {"id": id, "operated": 0, "areaId": areaId});
    });
    main.on('click', '.del_btn', function () { //删除
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "delete",
            "name": '删除',
            "url": "/poorVi/deletePoorVillage?id=" + id,
            "sub": true,
            "fn": function () {
                layer.msg("删除成功！")
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true');
    });
    main.on('click', '.refresh_btn', function () { //刷新
        getList()
    });

    //导入功能
    importUpload("/poorVi/insert", getList, pageNo, pageSize);

    main.on('click', ".export_btn", function () { //导出功能
        location.href = "poorVi/exportPoVillage?" + $("#searchForm").serialize();
    });

    //从编辑、查看页面返回，查询显示原先的查询结果
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val(),
            prevFrom = { //查询条件
                "cry": $('#cry').val(),
                "name": $('#name option:selected').text(),
                "year": $('#year').val(),
                "fpeople": $('#fpeople').val(),
                "contact": $('#contact').val(),
                "nature": $('#nature').val(),
                "development": $('#development').val(),
                "h-cry": $('#h-cry').val(),
                "h-name": $('#h-name').val()
            };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))
    })

    getList(pageNo, pageSize)

}

/*-- 贫困村新增、编辑、查看方法 --*/
function poorVillageEdit() {
    var id = mccms.getHash('id'), //用户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        areaId = mccms.getHash('areaId'), //地区ID
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        form = $('#editForm'),
        path = $('.c-primary'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数

        setNoticeToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/poorVi/getPoorVillage?id=" + id,
                "cache": false,
                "method": "POST",
                success: function (data) {
                    var data = data || {
                        result: {}
                    };
                    data.result.detail = operated,
                        setForm(data.result);
                }
            })
        },
        setAddToForm = function () {
            setForm()
        },
        setForm = function (data) { //填充表单
            var cryId;
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "editList",
                "container": form,
                "data": data,
                "callback": function () {
                    if (inquire == 1) { //inquire == 1从《账表查询》过来则修改模块名称
                        $("nav .menuLevel1").html("账表查询");
                        $("nav .menuLevel2").html("贫困村查询");
                        $("nav .c-primary").html("查看贫困村");
                    }
                    var txt = operated ? '查看贫困村' : '编辑贫困村';
                    id && path.html(txt), //修改模块名称
                        form.mcFormValide() //绑定表单验证


                    if (id) {
                        getList = function (pageNo, pageSize) {
                            mccms.ajax({
                                "url": "/helpTeam/getHelpTeamPersonByCondition",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "pageNo": pageNo,
                                    "pageSize": pageSize,
                                    "team.village.id": areaId
                                },
                                "success": function (data) {
                                    mccms.getHbs({
                                        "local": true,
                                        "hbsName": "List1",
                                        "container": $("#tbody1"),
                                        "data": data.result,
                                        "callback": function () {
                                            //分页方法
                                            PagingMethods(pageNo, pageSize, data, getList)
                                            //分页样式
                                            $("#pageContainer select").css({
                                                'width': '100%',
                                                'height': 'auto'
                                            })
                                        }
                                    })

                                }
                            })

                        }
                        getList(pageNo, pageSize)
                    }


                    scrollToBox('nav_item')

                    var countryVal, //定义乡
                        natrueVal, //定义村
                        nature, //定义村属性
                        developmentVal, //定义发展方向
                        terrainVal, //定义地形地貌
                        asphaltVal, //定义沥青（水泥）路
                        busVal; //定义客运班车

                    if (s_cry || s_name) {
                        countryVal = s_cry;
                        natrueVal = s_name;
                    }
                    if (data.cry) {
                        countryVal = data.cry; //获取到乡的值 
                    }
                    if (data.name) {
                        natrueVal = data.name; //获取到自然村的值  
                    }
                    if (data.nature) {
                        nature = data.nature; //获取村属性值 
                    }
                    if (data.development) {
                        developmentVal = data.development; //获取发展方向的值
                    }
                    if (data.terrain) {
                        terrainVal = data.terrain; //获取地形地貌的值
                    }
                    if (data.asphalt) {
                        asphaltVal = data.asphalt; //获取沥青（水泥）路的值
                    }
                    if (data.bus) {
                        busVal = data.bus; //获取客运班车的值
                    }


                    //根据获取的值，将自然村属性selected选中
                    $("#nature-ads option").each(function (i) {
                        if ($(this).val() == name) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#nature option").each(function (i) {
                        if ($(this).val() == nature) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#development option").each(function (i) {
                        if ($(this).val() == developmentVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#terrain option").each(function (i) {
                        if ($(this).val() == terrainVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#asphalt option").each(function (i) {
                        if ($(this).val() == asphaltVal) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    //根据获取的值，将自然村属性selected选中
                    $("#bus option").each(function (i) {
                        if ($(this).val() == busVal) {
                            $(this).attr("selected", "selected");
                        }
                    });

                    //10-11 wage add
                    mccms.ajax({
                        "url": "/area/findarea",
                        "cache": false,
                        "method": "POST",
                        "data": {
                            "fatherId": 3
                        },
                        success: function (data) {
                            var cryHtml = '<option value="" selected>请选择</option>';
                            for (var i = 0; i < data.result.length; i++) {
                                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                            }
                            $("#cry-add").html(cryHtml);
                            //编辑和查看下地区select框的填充
                            if (countryVal) { //乡的值填充
                                $("#cry-add option").each(function (i) {
                                    if ($(this).val() == countryVal) {
                                        $(this).attr("selected", "selected");
                                        $("#s-cry-add").val($(this).val());
                                        if (s_Level == 4 || s_Level == 5) {
                                            $("#cry-add").attr("disabled", "disabled");
                                        }
                                        cryId = $(this).attr("id");
                                        mccms.ajax({
                                            "url": "/area/findarea",
                                            "cache": false,
                                            "method": "POST",
                                            "data": {
                                                "fatherId": cryId
                                            },
                                            success: function (data) {
                                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                                for (var i = 0; i < data.result.length; i++) {
                                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                                }
                                                $("#naturals-add").html(naturalsHtml);
                                                if (natrueVal) { //村的值填充
                                                    $("#naturals-add option").each(function (i) {
                                                        if ($(this).val() == natrueVal) {
                                                            $(this).attr("selected", "selected");
                                                            if (s_Level == 4 || s_Level == 5) {
                                                                $("#cry-add").attr("disabled", "disabled");
                                                            }
                                                            cryId = $(this).attr("id");
                                                            $(this).attr("selected", "selected");
                                                            $("#s-naturals-add").val($(this).val());
                                                            if (s_Level == 5) {
                                                                $("#naturals-add").attr("disabled", "disabled");
                                                            }
                                                            var natrueNum = $(this).attr("data-number"); //选中村之后，自动填充村编号
                                                            var natureId = $(this).attr("id");
                                                            $("#natureId").val(natureId);
                                                            $("#code").val(natrueNum);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        }
                    });
                    $("#cry-add").change(function () {
                        cryId = $(this).find("option:checked").attr("id");
                        $("#s-cry-add").val($(this).find("option:checked").val());
                        mccms.ajax({
                            "url": "/area/findarea",
                            "cache": false,
                            "method": "POST",
                            "data": {
                                "fatherId": cryId
                            },
                            success: function (data) {
                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                for (var i = 0; i < data.result.length; i++) {
                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                }
                                $("#naturals-add").html(naturalsHtml);
                            }
                        });
                    });
                    $("#naturals-add").change(function () {
                        natrueNum = $(this).find("option:checked").attr("data-number"); //选中村之后，自动填充村编号
                        var natureId = $(this).find("option:checked").attr("id");
                        $("#s-natrueName-add").val($(this).find("option:checked").val());
                        $("#natureId").val(natureId);
                        $("#code").val(natrueNum);

                        $("#popup span[data-teamvillageid]").attr("data-teamvillageid", natureId) //当前选定村

                    });
                    //10-11 wage add
                }
            })

        },
        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/poorVi/updatePoorVillage" : "/poorVi/addPoorVillage"; //前者编辑API，后者新增API
            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "lock": true,
                "method": "POST",
                "beforeSend": function () {
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": function (data) {
                    if (data.message == '该地区是贫困村') {
                        layer.msg('该地区已是贫困村,请重新选择村！')
                    } else {
                        layer.msg(data.message)
                        id ? mccms.gobackFromEdit() : mccms.goBack()
                    }


                }
            })
        };

    // 流程
    id ? setNoticeToForm() : setAddToForm(),
        form.on('click', '.sub_btn', function () {
            myRequired("editForm", "popup");
            subMsg($(this));
        })

}


/*---- 扶贫主体管理 ----*/

/*-- 帮扶单位管理-帮扶单位 --*/
function helpUnitMng() {
    // 变量声明 
    var main = $('#mainList'),
        form = $('#searchForm'), //查询表单
        valid = form.valid(), //表单验证
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        countryCode = $("input[name=cry]").attr("data-id"); //乡的areaCode编码;用做权限控制
    if (!countryCode) {
        countryCode = ""
    } //当用户为县以及以上级别时,不做权限控制
    var getList = function (pageNo, pageSize, checkType) {
        areaSelected(cryVal, nameVal, checkType, function () {
            valid &&
            mccms.ajax({ //查询帮扶单位API
                "url": "/helpu/findAllhelpunits",
                "cache": false,
                "method": "POST",
                "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list1",
                        "container": $("#tbody1"),
                        "data": data.result,
                        "callback": function () {

                            cryAndNameChange() //乡村下拉
                            //回显查询条件
                            var hCryCode = $("#h-cry").val() //乡的areaCode值
                            if (hCryCode) {
                                $("#cry option").each(function (index, item) {
                                    if (hCryCode == $(this).attr("data-number")) {
                                        $(this).attr("selected", true)
                                    }
                                })

                            }


                            //点击数据项添加背景色
                            var oneID = $('#tbody1 input[name=radio]:checked')
                            $("#tbody1 input").on("click", function () {
                                var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id
                                helpUnitDonePairing(id); //帮扶单位对应已结对行政村方法
                            })


                            //分页方法
                            PagingMethods(pageNo, pageSize, data, getList)

                            //改变td line-height
                            $("#tbody1 tr td").css("line-height", "27px")
                        }
                    });

                }
            })
        })

    }

    //帮扶单位新增
    var helpUnitMngAdd = function (id, isDetail, isEdit) {
        if (!pageNo) {
            var pageNo = 1
        }
        var form = $('#addForm'),
            setForm = function (data) { //填充表单
                var data = data || {};
                if (isDetail) {
                    mccms.ajax({
                        "url": "/helpu/gethelpunitById",
                        "method": "POST",
                        "data": {
                            id: id
                        },
                        "success": function (data) {
                            if (isEdit) {
                                data.result.detail = 0; //1为查看不可编辑,0为可编辑
                            } else {
                                data.result.detail = 1
                            }
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "addList",
                                "container": form,
                                "data": data.result,
                                "callback": function () {
                                    getW(data)
                                    form.mcFormValide(); //绑定表单验证
                                    $('.sub_btn').on('click', function () {
                                        subMsg();
                                    })
                                }
                            })
                        }
                    })
                } else {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "addList",
                        "container": form,
                        "data": data,
                        "callback": function () {
                            getW()
                            form.mcFormValide(); //绑定表单验证
                            $('.sub_btn').on('click', function () {
                                subMsg();
                            })
                        }
                    })
                }
            },
            subMsg = function () { //提交用户数据
                var data = form.serialize(),
                    valid = form.valid();
                // if (s_province) {
                //     data += '&province=' + $('#province1').val()
                // }
                // if (s_city) {
                //     data += '&city=' + $('#city').val()
                // }
                pageNo = $('#pageCount option:selected').val()
                pageSize = $('#pageSize option:selected').val()
                if (s_cty) {
                    data += '&county=' + $('#county').val()
                }
                if (s_cry) {
                    data += '&country=' + $('#country').val()
                }
                if (isEdit) {
                    data += '&id=' + id
                    valid &&
                    mccms.ajax({
                        "url": "/helpu/updatehu",
                        "method": "POST",
                        "data": data,
                        "success": function () {
                            getList(pageNo, pageSize); //刷新
                            layer.closeAll(); //关闭弹窗
                        }
                    })
                } else {
                    valid &&
                    mccms.ajax({
                        "url": "/helpu/addhelpunits",
                        "method": "POST",
                        "data": data,
                        "success": function () {
                            getList(pageNo, pageSize); //刷新
                            layer.closeAll(); //关闭弹窗
                        }
                    })
                }
            },
            getW = function (params) {
                //省
                mccms.ajax({
                    "url": "/area/findarea",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "fatherId": 0 //3代表魏县的id
                    },
                    success: function (data) {
                        var cryHtml;
                        for (var i = 0; i < data.result.length; i++) {
                            cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                        }
                        $("#province1").html(cryHtml);
                        if (params) {
                            $("#province1").val(params.result.province)
                        } else {
                            $("#province1").val(s_province)
                        }
                        if (s_province_id) {
                            $("#province1").attr('disabled', 'disabled')
                        }
                    }
                });
                //市
                mccms.ajax({

                    "url": "/area/findarea",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "fatherId": 1
                    },
                    success: function (data) {
                        var naturalsHtml;
                        for (var i = 0; i < data.result.length; i++) {
                            naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                        }
                        $("#city").html(naturalsHtml);
                        if (params) {
                            $("#city").val(params.result.city)
                        } else {
                            $("#city").val(s_city)

                        }
                        if (s_city_id) {
                            $("#city").attr('disabled', 'disabled')
                        }
                    }
                });

                //县
                mccms.ajax({
                    "url": "/area/findarea",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "fatherId": 2
                    },
                    success: function (data) {
                        var naturalsHtml;
                        for (var i = 0; i < data.result.length; i++) {
                            naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                        }
                        $("#county").html(naturalsHtml);
                        if (params) {
                            $("#county").val(params.result.county)
                        } else {
                            $("#county").val(s_cty)

                        }
                        if (s_cty_id) {
                            $("#county").attr('disabled', 'disabled')
                        }
                        mccms.ajax({
                            "url": "/area/findarea",
                            "cache": false,
                            "method": "POST",
                            "data": {
                                "fatherId": 3
                            },
                            success: function (data) {
                                var naturalsHtml = '<option value="">请选择</option>';
                                for (var i = 0; i < data.result.length; i++) {
                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                }
                                $("#country").html(naturalsHtml);
                                if (params) {
                                    $("#country").val(params.result.country)
                                } else {
                                    $("#country").val(s_cry)

                                }
                                if (s_cry_id) {
                                    $("#country").attr('disabled', 'disabled')
                                }
                            }
                        });
                        $("#county").change(function () {
                            var countyId = $(this).find("option:checked").attr("id");
                            //乡
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": countyId
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="">请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#country").html(naturalsHtml);
                                    $("#country").val(s_cry)
                                    if (s_cry_id) {
                                        $("#country").attr('disabled', 'disabled')
                                    }
                                }
                            });
                        })
                    }
                });

            }
        setForm();
    }

    //帮扶单位删除
    var helpUnitMngDel = function (id) {
        if (!pageNo) {
            var pageNo = 1
        }
        mccms.operation({
            "method": "POST",
            "name": '删除',
            "url": "/helpu/delecthelpunits?id=" + id,
            "sub": true,
            "fn": function () {
                getList(pageNo, pageSize); //刷新
            }
        })
    }


    // 流程
    main.on('click', '.query-btn', function () { //帮扶单位查询
        getList(pageNo, pageSize, true);
    });

    main.on('click', '.add_btn', function () { //新增
        //弹窗方法
        layer.open({
            type: 1,
            area: ['80%', '80%'],
            title: '新增',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#addPopup')
        })
        helpUnitMngAdd();
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id
        if (!id) {
            layer.msg('请先勾选帮扶单位')
            return false
        }
        //弹窗方法
        layer.open({
            type: 1,
            area: ['80%', '80%'],
            title: '查看',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#addPopup')
        })
        helpUnitMngAdd(id, true)
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id
        if (!id) {
            layer.msg('请先勾选帮扶单位')
            return false
        }
        //弹窗方法
        layer.open({
            type: 1,
            area: ['80%', '80%'],
            title: '编辑',
            shade: 0.5,
            moveType: 1,
            shift: 0,
            content: $('#addPopup')
        })
        helpUnitMngAdd(id, true, true)
    });
    main.on('click', '.del_btn', function () { //删除
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id
        if (id) {
            helpUnitMngDel(id);
        } else {
            layer.msg("请先选择帮扶单位！");
        }
    });
    main.on('click', '.pairing_btn', function () { //结对弹窗
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id   
        if (id) {
            layer.open({ //弹窗方法 
                type: 1,
                area: ['80%', '80%'],
                title: '帮扶单位与行政村结对',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('#twinningPopup'),
                success: function () {
                    $(".layui-layer .layui-layer-content").css("height", "94%")
                    //清空乡村
                    $('#cry2').val('')
                    $('#name2').val('')
                    twinningVillagesAll(); //刷所有行政村页面
                }
            })

        } else {
            layer.msg("请先选择帮扶单位！")
        }

    });
    main.on('click', '.del_pairing_btn', function () { //结对解除
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id   
        var idArr = []; //选定状态的多选框

        $('#tbody2 input[name="checkbox"]:checked').each(function () {
            idArr.push(parseInt($(this).attr("id")));
        });

        memberArr = JSON.stringify(idArr);
        memberArr = memberArr.substring(1, memberArr.length - 1);
        if (id && memberArr) {
            //询问框
            layer.confirm('解除结对将同时删除驻村人员关系', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                layer.msg("解除结对成功！")
                helpUnitDelPairing(id, memberArr); //结对解除 
            })
        } else {
            layer.msg("请先选择帮扶单位与行政村");
        }
    });
    //导入方法
    importUpload("/helpu/insert", getList, pageNo, pageSize)

    getList(pageNo, pageSize, true)

}

/*-- 帮扶单位管理-帮扶单位与行政村结对-行政村弹窗列表信息--*/
function twinningVillagesAll() {
    // 变量声明 
    var main = $('#mainList'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        cryName,
        villageName,
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            areaSelected(cryVal, nameVal, checkType, function () { //areaSelected() 权限控制方法
                mccms.ajax({ //行政村查询
                    "url": "/poorVi/queryVillages",
                    "cache": false,
                    "method": "POST",
                    "data": $("#twinning").serialize() + "&pageNo=" + pageNo + "&pageSize=" + 10,
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list3",
                            "container": $("#tbody3"),
                            "data": data.result,
                            "callback": function () {
                                $(".pairing_sub_btn").unbind(); //消除多次绑定
                                $(".pairing_sub_btn").on("click", function () { //结对保存
                                    helpUnitPairing();
                                    // $('#cry2').val('')
                                    // $('#name2').val('')
                                });
                                $('#checkAll').attr('checked', false) //刷新数据去除全选状态
                                mccms.checkAll() //全选控制

                                //乡
                                mccms.ajax({
                                    "url": "/area/findarea",
                                    "cache": false,
                                    "method": "POST",
                                    "data": {
                                        "fatherId": 3 //3代表魏县的id
                                    },
                                    success: function (data) {
                                        var naturalsHtml = '<option value="" class="please">请选择</option>';
                                        for (var i = 0; i < data.result.length; i++) {
                                            naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                        }
                                        $("#cry2").html(naturalsHtml).val(cryVal);
                                        if (!cryVal) {
                                            $("#cry2").val(cryName)
                                        }

                                        $("#cry2").off().change(function () {
                                            cryName = $("#cry2").val();
                                            var countryId = $("#cry2 option:selected").attr('id');
                                            mccms.ajax({
                                                "url": "/area/findarea",
                                                "cache": false,
                                                "method": "POST",
                                                "data": {
                                                    "fatherId": countryId
                                                },
                                                "success": function (data) {
                                                    //填充村数据
                                                    var nameHtml = '<option value="" class="please">请选择</option>';
                                                    for (var i = 0; i < data.result.length; i++) {
                                                        nameHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                                    }
                                                    $("#name2").html(nameHtml)

                                                    //乡村选择后刷新列表
                                                    regRefresh()

                                                }
                                            })


                                        })


                                    }
                                })

                                //村
                                $('#name2').off().change(function () {
                                    regRefresh()
                                });

                                //乡村选择后刷新方法
                                function regRefresh() {
                                    mccms.ajax({ //行政村查询
                                        "url": "/poorVi/queryVillages",
                                        "cache": false,
                                        "method": "POST",
                                        "data": $("#twinning").serialize() + "&pageNo=" + 1 + "&pageSize=" + 10,
                                        "success": function (data) {
                                            mccms.getHbs({
                                                "local": true,
                                                "hbsName": "list3",
                                                "container": $("#tbody3"),
                                                "data": data.result
                                            })
                                            $('#checkAll').attr('checked', false) //刷新数据去除全选状态
                                            mccms.pageHtml(data, getList, [], "layPage3")
                                        }
                                    })
                                }

                            }
                        })
                        mccms.pageHtml(data, getList, [], "layPage3")
                    }
                })

            })
        }
    getList(pageNo, pageSize, true)
    $('.layui-layer-close').on('click', function () { //关闭结对弹窗时清空查询条件
        $('#cry2').val('')
        $('#checkAll').attr('checked', false) //刷新数据去除全选状态
    })

}

/*-- 帮扶单位-结对保存方法--*/
function helpUnitPairing() {
    if (!pageNo) {
        var pageNo = 1
    }
    ;
    var helpPersonid = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态扶贫单位id
    var idArr = []; //选定状态的多选框
    $('#tbody3 input[name="checkbox3"]:checked').each(function () {
        idArr.push(parseInt($(this).attr("id")));
    });

    if (idArr.length == 0) {
        layer.msg('请勾选行政村');
        return false;
    }

    memberArr = JSON.stringify(idArr);
    memberArr = memberArr.substring(1, memberArr.length - 1);

    //提交用户数据
    mccms.ajax({
        "url": "/helppeson/addhelpoor?helpPersonid=" + helpPersonid,
        "cache": false,
        "dataType": "json",
        "method": "POST",
        "contentType": "application/json",
        "data": {
            "sid": memberArr
        },
        "success": function () {
            helpUnitDonePairing(helpPersonid); //刷新
            layer.closeAll(); //关闭弹窗 
        }
    })

}

/*-- 帮扶单位管理-结对解除方法 --*/
function helpUnitDelPairing(id, memberArr) {
    var helpPersonid = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态扶贫单位id
    //提交结对解除数据
    mccms.ajax({
        "url": "/helppeson/removeAddhelpoors?id=" + id,
        "cache": false,
        "dataType": "json",
        "method": "POST",
        "contentType": "application/json",
        "data": {
            "sid": memberArr
        },
        "success": function () {
            helpUnitDonePairing(helpPersonid); //刷新
        }
    })

}

/*-- 帮扶单位管理-帮扶单位对应已结对行政村方法 --*/
function helpUnitDonePairing(id) {
    // 变量声明 
    var size = 10,
        no = 1,
        pageCount = null;
    var getList = function (pageNo, pageSize) {
        var pageNo;
        if (!pageNo) {
            pageNo = 1
        }
        mccms.ajax({
            "url": "/poorVi/getPoorVillages?id=" + id,
            "cache": false,
            "method": "POST",
            "data": {
                "pageNo": pageNo,
                "pageSize": pageSize
            },
            "success": function (data) {

                mccms.getHbs({
                    "local": true,
                    "hbsName": "list2",
                    "container": $("#tbody2"),
                    "data": data,
                    "callback": function () {
                        //数据条添加背景色
                        tdAddBg('tbody2');

                        //改变td line-height
                        $("#tbody2 tr td").css("line-height", "27px")

                    }
                });


            }
        })
    };


    getList(no, size);
}


/*-- 驻村工作队管理 start caiwen 2017-10-14 --*/

/*-- 驻村工作队管理-帮扶单位 --*/
function villageTeamMng() {
    // 变量声明 
    var main = $('#mainList'),
        form = $('#searchForm'), //查询表单
        valid = form.valid(), //表单验证
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        countryCode = $("input[name=cry]").attr("data-id"); //乡的areaCode编码;用做权限控制
    if (!countryCode) {
        countryCode = ""
    } //当用户为县以及以上级别时,不做权限控制
    var getList = function (pageNo, pageSize) {
        mccms.ajax({
            "url": "/helpu/findAllhelpunits",
            "cache": false,
            "method": "POST",
            "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&country=" + countryCode,
            "success": function (data) {
                mccms.getHbs({
                    "local": true,
                    "hbsName": "list1",
                    "container": $("#tbody1"),
                    "data": data.result,
                    "callback": function () {
                        //点击数据项添加背景色 
                        tdAddBg('tbody1')

                        $("#tbody1 input").on("click", function () {
                            var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id   
                            villageTeamHelpUnitDonePairing(id); //帮扶单位对应已结对行政村方法

                        })

                        //分页方法
                        PagingMethods(pageNo, pageSize, data, getList)

                        //改变td line-height
                        $("#tbody1 tr td").css("line-height", "27px")

                    }
                });
            }
        })
    }

    // 流程  
    main.on('click', '.query-btn', function () { //帮扶单位查询
        getList(pageNo, pageSize) //查询后刷新页面
    });
    main.on('click', '.setTeamPopup_btn', function () { //组建工作队弹窗
        var id = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id   
        var villageiId = $('#tbody2 input[name=radio2]:checked').attr("id"); //选定状态已结对行政村id   
        if (villageiId) {
            layer.open({ //弹窗方法 
                type: 1,
                area: ['80%', '90%'],
                title: '组建工作队',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('#setTeamPopup'),
                success: function () {
                    laydate.render({
                        elem: '#startTime' //开始时间
                    })
                    laydate.render({
                        elem: '#endTime' //开始时间
                    })

                    $(".layui-layer .layui-layer-content").css("height", "94%")
                }
            })
            villageTeamSetTeam(); //组件工作队-帮扶负责人列表

        } else {
            layer.msg("请先选择帮扶单位与已结对行政村！")
        }

    });
    getList(pageNo, pageSize)

}

/*帮扶单位管理-帮扶单位对应已结对行政村方法*/
function villageTeamHelpUnitDonePairing(id) {
    // 变量声明 
    var getList = function (pageNo) {
        var pageNo = pageNo || mccms.getHash('pageNo') || mccms.stepCache.pageNo;
        if (!pageNo) {
            pageNo = 1
        }
        mccms.ajax({
            "url": "/poorVi/getPoorVillages?id=" + id,
            "cache": false,
            "method": "POST",
            "data": {
                "pageNo": pageNo,
                "pageSize": 10
            },
            "success": function (data) {
                mccms.getHbs({
                    "local": true,
                    "hbsName": "list2",
                    "container": $("#tbody2"),
                    "data": data,
                    "callback": function () {
                        //点击数据项添加背景色 
                        tdAddBg('tbody2')

                        //改变td line-height
                        $("#tbody2 tr td").css("line-height", "27px")
                    }
                });
                mccms.pageHtml(data, getList, [], "layPage2");

            }
        })
    };
    getList();
}

/*驻村工作队管理-组建工作队列表*/
function villageTeamSetTeam() {
    var unitId = $('#tbody1 input[name=radio]:checked').attr("id"); //选定状态帮扶单位id   
    var villageiId = $('#tbody2 input[name=radio2]:checked').attr("id"); //选定状态已结对行政村id   
    // 变量声明 
    var main = $('#mainList'),
        getList = function (pageNo) {
            var pageNo;
            if (!pageNo) {
                pageNo = 1
            }
            mccms.ajax({
                "url": "/helppeson/getHelpPresonsNotInTeam",
                "cache": false,
                "method": "POST",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": 10,
                    "unitId": unitId,
                    "villageId": villageiId
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list3",
                        "container": $("#tbody3"),
                        "data": data.result,
                        "callback": function () {
                            $(".sub_btn").unbind(); //消除多次绑定
                            $(".sub_btn").on("click", function () { //组建工作队-保存
                                var helpPersonId = $('#setTeamPopup #tbody3 input[name=radio3]:checked').attr("value"); //选定状态帮扶负责人id
                                var captain = $("#setTeamForm select[name=captain]").val();
                                var firstSecretary = $("#setTeamForm select[name=firstSecretary]").val();
                                var startTime = $("#setTeamForm .startTime").val();
                                var endTime = $("#setTeamForm .endTime").val();

                                if (helpPersonId && captain && firstSecretary && startTime && endTime) {
                                    if (startTime > endTime) {
                                        layer.msg("开始时间不能大于结束时间")
                                    } else {
                                        setTeamKeep();
                                    }

                                } else {
                                    layer.msg("请选择负责人并填写信息")
                                }
                            })
                            mccms.pageHtml(data, getList, [], "layPage3");
                            setTeamReset(); //保存方法


                        }

                    });
                }
            })

        };

    getList();
    //组建工作队-保存方法
    var setTeamKeep = function () {
        // 变量声明
        var helpPersonId = $('#tbody3 input[name=radio3]:checked').attr("value"); //选定状态帮扶负责人id 

        var form = $('#setTeamForm'), //输入表单
            valid = form.valid(), //表单验证
            keep = function (pageNo) {
                if (!pageNo) {
                    pageNo = 1
                }
                valid &&
                mccms.ajax({
                    "url": "/helpTeam/addHelpTeamPerson",
                    "cache": false,
                    "method": "POST",
                    "data": $("#setTeamForm").serialize() + "&team.unit.id=" + unitId + "&team.village.id=" + villageiId + "&helpPerson.id=" + helpPersonId + "&pageNo=" + pageNo + "&pageSize=" + 10,
                    "success": function (data) {

                        layer.closeAll(); //关闭弹窗
                        layer.msg("保存成功！")
                        getList(); //刷新
                    }
                })
            };
        keep();
    }
}

/*组建工作队-帮扶负责人-单选刷新输入框方法*/
function setTeamReset() {
    $("#setTeamPopup input[type=radio]").on("click", function () {
        $("#setTeamPopup select,#startTime,#endTime").val("")
    })
}

/*-- 驻村工作队管理 end caiwen 2017-10-14 --*/

/*--- 驻村人员管理 start caiwen 2017-10-14 --*/
function villagePersonMng() {
    // 变量声明 
    var main = $('#mainList'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        urlStr = "&cry=" + s_cry_id + "&name=" + s_name,
        cryShow, //乡改变后显示值
        nameShow,
        /* flag = true,*/
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                var villageId = $("#searchForm #name").find("option:selected").attr("id"); //村id,用于查询功能
                mccms.ajax({
                    "url": "/helpTeam/getHelpTeamPersonByCondition",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "pageNo": pageNo,
                        "pageSize": pageSize,
                        "cry": $("#h-cry").val(), //乡
                        "team.village.id": villageId //村
                    },
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "List",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {

                                //点击数据项添加背景色 
                                tdAddBg('tbody')

                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);

                                /* if (flag) { //若删除之后数据非空，则查询条件依旧显示
                                     if (!cryVal) {
                                         $('#cry').val(cryShow)
                                     }
                                     if (!nameVal) {
                                         $('#name').val(nameShow)
                                     }
                                 }*/

                                //乡选中加载村数据
                                $("#cry").change(function () {
                                    cryId = $(this).find("option:checked").attr("id");
                                    cryAreaCode = $(this).find("option:checked").attr("data-number"); //乡的地区编码值
                                    $("#h-cry").val(cryAreaCode)
                                    cryShow = $(this).val()
                                    mccms.ajax({
                                        "url": "/area/findarea",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            "fatherId": cryId
                                        },
                                        success: function (data) {
                                            var naturalsHtml = '<option value="" selected>请选择</option>';
                                            for (var i = 0; i < data.result.length; i++) {
                                                naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].id + '">' + data.result[i].area + '</option>';
                                            }
                                            $("#name").html(naturalsHtml);
                                        }
                                    });
                                });
                                //村选中加载村数据
                                $("#name").change(function () {
                                    /*nameVal = $(this).find("option:checked").val();*/
                                    nameShow = $(this).find("option:checked").val()
                                });

                            }
                        });


                    }
                })
            });
        }

    // 流程
    main.on('click', '.queryBtn', function () { //驻村人员查询
        getList(pageNo, pageSize, 'true'); //查询后刷新页面         
    });

    main.on('click', '.del_btn', function () { //删除

        var id = $(this).parents('td').attr('id');
        cryVal = $('#cry').find('option:selected').val()
        mccms.operation({
            "method": "post",
            "asycn": false,
            "name": '删除该驻村人员',
            "url": "/helpTeam/removeHelpTeamPersonById",
            "data": {
                "id": id
            },
            "sub": true,
            "fn": function () { //若删除的数据为最后一条，条件重置，删除之后初始化查询全部数据

                /*if (!flag) {
                    $("#h-cry").val('')
                    $('#cry').val('')
                    $('#name').val("")
                }*/
                getList(pageNo, pageSize) //保存后刷新页面
            }
        })
    })

    getList(pageNo, pageSize)
}


/*--kaibin helpPersonLiableMng start 20171012--*/

/*--帮扶责任人管理--*/
function helpPersonLiableMng() {
    // 变量声明
    var main = $('#MainList'),
        //帮扶单位数据展示
        form = $('#searchForm'), //查询表单
        valid = form.valid(), //表单验证
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        countryCode = $("input[name=cry]").attr("data-id"); //乡的areaCode编码;用做权限控制
    if (!countryCode) {
        countryCode = ""
    } //当用户为县以及以上级别时,不做权限控制
    //主页面数据展示
    var getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                mccms.ajax({
                    "url": "/helpu/findAllhelpunits",
                    "cache": false,
                    "method": "POST",
                    "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list1",
                            "container": $("#tbody1"),
                            "data": data.result,
                            "callback": function () {
                                //乡村下拉方法
                                cryAndNameChange()

                                //回显查询条件
                                var hCryCode = $("#h-cry").val() //乡的areaCode值
                                if (hCryCode) {
                                    $("#cry option").each(function (index, item) {
                                        if (hCryCode == $(this).attr("data-number")) {
                                            $(this).attr("selected", true)
                                        }
                                    })

                                }
                                //点击数据项添加背景色 
                                tdAddBg('tbody1')

                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList)

                                //改变td line-height
                                $("#tbody1 tr td").css("line-height", "27px")
                            }
                        });
                    }
                })
            })

        },
        //帮扶负责人数据展示
        getList1 = function (id, unitname) {
            mccms.ajax({
                "url": "/helpu/findhelpunits",
                "cache": false,
                "method": "POST",
                "data": {
                    id: id
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list2",
                        "container": $("#tbody2"),
                        "data": data,
                        "callback": function () {
                            tdAddBg('tbody2')

                            //帮扶负责人删除
                            $(".del_btn", "#tbody2").off().on('click', function () {
                                //获取当条记录的id
                                id = $(this).attr("data-id")
                                mccms.ajax({ //查询帮扶负责人是否已组建工作队API
                                    "url": "/helppeson/helppesonJudge",
                                    "cache": false,
                                    "method": "POST",
                                    "data": {
                                        id: id
                                    },
                                    "success": function (data) {
                                        if (data.result) {
                                            layer.msg("请先解除驻村人员结对关系，再进行删除！")
                                        } else {
                                            //询问框
                                            layer.confirm("是否删除该帮扶责任人?", {
                                                btn: ['确定', '取消'] //按钮
                                            }, function () {
                                                mccms.ajax({ //删除帮扶负责人API
                                                    "url": "/helppeson/delecthelppeson",
                                                    "cache": false,
                                                    "method": "POST",
                                                    "data": {
                                                        id: id
                                                    },
                                                    "success": function (data) {
                                                        var id = $('#tbody1 input[name=radio]:checked').attr("value"); //当前帮扶单位id  
                                                        getList1(id, unitname); //保存后刷新页面
                                                        layer.msg(data.message)
                                                    }
                                                })

                                            }, function () {
                                                // layer.msg("已取消！")
                                            })
                                        }


                                        //删除帮扶负责人API
                                        // mccms.operation({
                                        //     "method": "POST",
                                        //     "name": title,
                                        //     "url": "/helppeson/delecthelppeson",
                                        //     "data": {
                                        //         "id": id
                                        //     },
                                        //     "sub": true,
                                        //     "fn": function() {
                                        //         var id = $('#tbody1 input[name=radio]:checked').attr("value"); //当前帮扶单位id  
                                        //         getList1(id, unitname); //保存后刷新页面
                                        //         layer.msg('删除成功！')
                                        //     }
                                        // })

                                    }
                                })
                            });
                            //帮扶负责人编辑
                            $(".detail_btn").on('click', function () {
                                //获取当条记录的id
                                id = $(this).attr("data-id");
                                mccms.ajax({
                                    "url": "/helppeson/findhelppeson",
                                    "cache": false,
                                    "method": "POST",
                                    "data": {
                                        "id": id
                                    },
                                    "success": function (data) {
                                        subForm(data.result, "/helppeson/updatehelppeson", "修改")
                                    }
                                })
                            });


                            //结对关系
                            $(".PairingNexus_btn").on('click', function () {
                                var id = $(this).attr("data-id"); //帮扶负责人id
                                layer.open({
                                    type: 1,
                                    area: ['80%', '80%'],
                                    title: "结对关系",
                                    shade: 0.5,
                                    moveType: 1,
                                    shift: 0,
                                    content: $('#PairingNexus'),
                                    success: function () {
                                        mccms.ajax({ //查询指定帮扶责任人所帮扶的贫困户API
                                            "url": "/helppeson/listPoorFamilyByHelpPerson",
                                            "cache": false,
                                            "method": "POST",
                                            "data": {
                                                "helpPersonID": id
                                            },
                                            "success": function (data) {
                                                mccms.getHbs({
                                                    "local": true,
                                                    "hbsName": "list3",
                                                    "container": $("#tbody3"),
                                                    "data": data
                                                })
                                            }
                                        })

                                    }
                                })

                            });


                        }
                    });

                }
            })

        },
        subForm = function (data, url, text) {
            /*data:弹窗的模板数据调用
            url:点击保存的接口
            text: 弹窗标题显示*/
            layer.open({
                type: 1,
                area: ['80%', '80%'],
                title: text,
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('#add'),
                success: function () {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "addTpl",
                        "container": $("#add"),
                        "data": data,
                        "callback": function () {
                            $(".save-btn", '#add').off().on('click', function () {
                                var unitname = $('#tbody1 input[name=radio]:checked').attr("unitname"); //帮扶单位名称
                                var valid = $("#form1").valid()
                                if (valid) {
                                    //编辑保存
                                    var index = layer.index;
                                    mccms.ajax({
                                        "url": url,
                                        "cache": false,
                                        "method": "POST",
                                        "data": $("#form1").serialize() + "&unit_name=" + unitname,
                                        "success": function (data) {
                                            getList1(id, unitname); //刷新
                                            layer.closeAll(); //关闭弹窗 
                                            layer.msg("保存成功!")
                                        }
                                    })
                                } else {
                                    return false
                                }
                            })
                        }
                    });

                }
            });

        }
    // 流程
    main.on('click', '.query-btn', function () { //帮扶单位查询
        getList(pageNo, pageSize, true); //查询后刷新页面
    });

    //选中帮扶单位显示对应帮扶负责人
    main.on('click', "input[name=radio]", function () {
        id = $(this).val();
        var unitname = $(this).attr("unitname"); //帮扶单位名称
        getList1(id, unitname);

    });

    //点击新增弹窗
    $('#add-btn').on('click', function () {
        var HELP_UNIT = $('#tbody1 input[name=radio]:checked').val(); //选定状态帮扶单位id
        HELP_UNIT ? subForm("", "/helppeson/addhelppeson?HELP_UNIT=" + HELP_UNIT, "新增") : layer.msg("请先选择帮扶单位")
    })
    getList(pageNo, pageSize, true)
}

/*--kaibin helpPersonLiableMng end 20171012--*/

/*嘉欣JavaScript end 0929*/

/*--贫困户管理--*/
function povertyStrickenMng() {
    // 变量声明
    var main = $('#MainList'),
        addMain = $('#addPopup'),
        modelForm = $('#modelForm'),
        memberArr = [],
        operated = 0,
        detail = 0,
        isEdit = 0,
        village1Id = null,
        _id = null,
        addTime = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        urlStr = "&cry=" + s_cry + "&name=" + s_name,
        Rolebutton = [], //角色可显按钮，不同角色能够显示的操作按钮不同
        // id ：操作记录的id
        // operated 0为返贫，1为脱贫
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        changePop = function (id, operated) {
            layer.open({
                type: 1,
                area: ['530px', '500px'],
                title: '变更情况',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('.change-box'),
                success: function () {
                    //form-change
                    var myDate = new Date();
                    $("#change-date").val(myDate.toLocaleDateString());
                    $("#changes-type").val(operated);
                    $("#reason").val("");
                    $(".input-btn", ".change-box").off().on('click', function () {

                        var holdPageNo = $("#pageCount").val(); //保存时当前第几页
                        var holdPageSize = $("#pageSize").val(); //保存时每页行数

                        $("#changes-type").removeAttr("disabled");
                        var index = layer.index;
                        mccms.ajax({
                            "url": "/ridPo/addRidPoor",
                            "cache": false,
                            "method": "POST",
                            "data": $("#form-change").serialize() + "&pid=" + id,
                            "success": function (data) {
                                layer.close(index);
                                layer.msg('操作成功！')
                                getList(holdPageNo, holdPageSize)
                            }
                        })
                    })
                }
            })
        },

        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                //脱贫状态
                var povertyCheckbox = $("#poverty .povertyCheckbox");
                var povertyVal = [];
                $("#poverty .povertyCheckbox").each(function () {
                    if ($(this).prop("checked")) {
                        povertyVal.push($(this).val())
                    }
                })

                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    // backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&poverty=" + povertyVal.join()
                }
                mccms.ajax({
                    "url": "/poorFa/queryPoorFamily",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        //乡选中加载村数据
                        $("#cry").change(function () {
                            cryId = $(this).find("option:checked").attr("id");
                            cryVal = $(this).find("option:checked").val();
                            $("#h-cry").val($(this).find("option:checked").attr("data-number"))
                            $("#h-name").val("") //清空村值
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": cryId
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="" selected>请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#name").html(naturalsHtml);
                                }
                            });
                        });

                        //村选中加载村数据
                        $("#name").change(function () {
                            nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
                            s_name_id = $(this).find("option:checked").attr("data-number");
                            $('#h-name').val(s_name_id)
                        });

                        data.result.resultList.forEach(function (ele, index) { //将角色的按钮权限作为字段添加到数据中
                            data.result.buttonPermissionList.forEach(function (botton) {
                                ele[botton] = botton; //获取数据项的编辑查看等按钮权限

                            })
                        })
                        data.result.buttonPermissionList.forEach(function (botton) {
                            data.result[botton] = botton; //获取数据的查询、导入导出等按钮权限
                        })

                        mccms.getHbs({
                            "local": true,
                            "hbsName": "buttonList",
                            "container": $("#button-List"),
                            "data": data.result,
                            "callback": function () {
                            }
                        });

                        /*处理数据结构 start*/
                        for (var i = 0; i < data.result.resultList.length; i++) {
                            var familyLen = 0; //实际家庭成员数量
                            for (var j = 0; j < data.result.resultList[i].family.length; j++) {
                                var poorFamily = data.result.resultList[i]
                                var family = data.result.resultList[i].family[j]
                                var relation = family.relation; //与户主关系
                                var isDel = family.isDel; //isDel是否删除 

                                if (isDel == '0' && relation == '户主') {
                                    poorFamily.hName = family.name;
                                    poorFamily.hNumber = family.number;
                                    poorFamily.hIdNumber = family.idNumber;
                                }
                                if (isDel == "0") {
                                    familyLen++;
                                    data.result.resultList[i].count = familyLen;
                                }
                            }

                        }
                        console.log(data.result.resultList)
                        /*处理数据结构 end*/


                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list1",
                            "container": $("#tbody1"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == "cry") {
                                            $('#cry option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-cry").val($(this).attr("data-number")) //乡code值回显
                                                }
                                            })
                                            cryVal = prevFrom[i] //乡赋值，用于分页点击之后回显
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            $('#name option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-name").val($(this).attr("data-number")) //村code值回显
                                                }
                                            })
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");

                                //点击数据项添加背景色 
                                tdAddBg('tbody1')

                                //分页方法
                                // PagingMethods(pageNo, pageSize, data, getList)

                                //选择年度
                                laydate.render({
                                    elem: '#year', //指定元素
                                    type: 'year'
                                })

                                //脱贫
                                $(".outPoor_btn").unbind("click");
                                $('.outPoor_btn').on('click', function () {

                                    //脱贫时改变value与text
                                    $("#changes-type .outinPoor").val("已脱贫").text("脱贫");

                                    var checkedNum = $("#form1").find("input[type=checkbox]:checked").length;
                                    if (checkedNum == 1) {
                                        var id = $("#form1").find("input[type=checkbox]:checked").val()
                                        changePop(id, 1)
                                    } else if (checkedNum < 1) {
                                        layer.msg("请选择一户贫困户")
                                        return false
                                    } else if (checkedNum > 1) {
                                        layer.msg("不能同时选择多个贫困户")
                                        return false
                                    }

                                })
                                //返贫
                                $(".inPoor_btn").unbind("click");
                                $('.inPoor_btn').on('click', function () {
                                    //脱贫时改变value与text
                                    $("#changes-type .outinPoor").val("未脱贫").text("返贫");

                                    var checkedNum = $("#form1").find("input[type=checkbox]:checked").length;
                                    if (checkedNum == 1) {
                                        var id = $("#form1").find("input[type=checkbox]:checked").val()
                                        changePop(id, 0)
                                    } else if (checkedNum < 1) {
                                        layer.msg("请选择一户贫困户")
                                        return false
                                    } else if (checkedNum > 1) {
                                        layer.msg("不能同时选择多个贫困户")
                                        return false
                                    }

                                })
                            }
                        });
                    }
                })
            });
        },
        getW = function (params) {
            //省请求
            _ajaxW(0, function (data) {
                createOption(data, function (cryHtml) {
                    $(".province1").each(function (i, item) {
                        $(item).html(cryHtml)
                    })
                    //省判断选中
                    $('.province1').val(s_province)
                    if (s_province) {
                        $('#province1').attr('disabled', 'disabled')
                    }
                    //市请求
                    _ajaxW(1, function (data) {
                        createOption(data, function (cryHtml) {
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                            //市判断选中
                            $('.city').val(s_city)
                            if (s_city) {
                                $('#city1').attr('disabled', 'disabled')
                            }
                            //县请求
                            _ajaxW(2, function (data) {
                                createOption(data, function (cryHtml) {
                                    $(".county").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                    //县判断选中
                                    $('.county').val(s_cty)
                                    if (s_cty) {
                                        $('#county').attr('disabled', 'disabled')
                                    }
                                    //乡请求
                                    _ajaxW(3, function (data) {
                                        createOption(data, function (cryHtml) {
                                            $('#country').html(cryHtml)
                                            $('#country').val(s_cry)

                                            //村请求
                                            if (s_cry) {
                                                $('#country').attr('disabled', 'disabled')
                                            }
                                            if (params) {
                                                $('#province1').val(params.province)
                                                $('#city1').val(params.city)
                                                $('#county').val(params.county)
                                                $('#country').val(params.country)
                                            }
                                            var countryId = $('#country').find('option:checked').attr('id');
                                            if (params) {
                                                // s_cry_id = countryId
                                            }
                                            _ajaxW(s_cry_id, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                                $('#village1').val(s_name)
                                                if (s_name) {
                                                    $('#village1').attr('disabled', 'disabled')
                                                }
                                                if (params) {
                                                    $("#village1").val(params.village);
                                                }
                                                //村下拉
                                                $("#village1").change(function () {
                                                    village1Id = $(this).find("option:checked").attr("id");
                                                });
                                            })
                                        })
                                    })
                                    if (s_cry) {
                                        $('#country').attr('disabled', 'disabled')
                                    } else {
                                        //乡下拉
                                        $("#country").change(function () {
                                            var countryId = $(this).find("option:checked").attr("id");
                                            //村请求
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                            })
                                        });
                                    }
                                })
                            })
                        })
                    })
                })

                //省下拉
                $(".province1").change(function () {
                    var province1Id = $(this).find("option:checked").attr("id");
                    //市请求
                    _ajaxW(province1Id, function (data) {
                        createOption(data, function (cryHtml) {
                            // $("#city").html(cryHtml);
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                        })
                    })
                    //市下拉
                    $(".city").change(function () {
                        var cityId = $(this).find("option:checked").attr("id");
                        //县请求
                        _ajaxW(cityId, function (data) {
                            createOption(data, function (cryHtml) {
                                // $("#county").html(cryHtml);
                                $(".county").each(function (i, item) {
                                    $(item).html(cryHtml)
                                })
                            })
                        })
                        //县下拉
                        $(".county").change(function () {
                            var countyId = $(this).find("option:checked").attr("id");
                            //乡请求
                            _ajaxW(countyId, function (data) {
                                createOption(data, function (cryHtml) {
                                    // $("#country").html(cryHtml);
                                    $(".country").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                })
                            })
                            //乡下拉
                            $("#country").change(function () {
                                var countryId = $(this).find("option:checked").attr("id");

                                //村请求
                                _ajaxW(countryId, function (data) {
                                    createOption(data, function (cryHtml) {
                                        $("#village1").html(cryHtml);
                                    })
                                })

                                //村下拉
                                $("#village1").change(function () {
                                    village1Id = $(this).find("option:checked").attr("id");
                                });
                            });
                        });
                    });
                });
            })
        },
        _ajaxW = function (id, fn) {
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": id
                },
                success: function (data) {
                    return fn(data)
                }
            });
        },
        createOption = function (data, fn) {
            var cryHtml = '<option value="">请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
            }
            return fn(cryHtml)
        }

    // 流程
    ThisYear(); //当前年
    main.on('click', '.add_btn', function () { //新增
        mccms.goTo("povertyStrickenMng", "povertyStrickenEdit");
    })
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parent().attr('id'); //用户ID
        mccms.goTo("povertyStrickenMng", "povertyStrickenEdit", {"id": id, "operatedState": 1, "detail": 1}); //operatedState==1为查看不可编辑,0为可编辑
    })
    main.on('click', '.edit_btn', function () { //编辑
        id = $(this).parent().attr('id'); //用户ID
        addTime = $(this).parent().attr('attr-time');
        sessionStorage.addTime = addTime;
        mccms.goTo("povertyStrickenMng", "povertyStrickenEdit", {
            "id": id,
            "operatedState": 0,
            "detail": 1,
            "isEdit": 1,
            "addTime": addTime
        });
    })
    main.on('click', ".interview_btn", function () { //帮扶
        var poorFamilyId = $(this).parent().attr('id'); //用户ID
        mccms.goTo("povertyStrickenMng", "visitingRecord", {"poorFamilyId": poorFamilyId});
    })
    //删除
    main.on('click', '.del_btn', function () {
        var id = $(this).parent().attr('id');
        mccms.operation({
            "method": "POST",
            "name": '删除',
            "url": "/poorFa/deletePoorFamily",
            "data": {
                "id": id
            },
            "sub": true,
            "fn": function () {
                layer.msg('删除成功！')
                getList(pageNo, pageSize)
            } //确定后刷新页面
        })
    })
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true');
    })
    //刷新
    main.on('click', '.refresh_btn', function () {
        getList(pageNo, pageSize, 'true')
    })

    //bill 新增 街景设置
    main.on('click', '.Street_btn', function () {
        var id = $(this).parents('td').parents('tr').find(".helpTd").find("input").val();
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        var country = $(this).parents('td').parents('tr').find("td").eq(2).text();
        var village = $(this).parents('td').parents('tr').find("td").eq(3).text();

        mccms.goTo("povertyStrickenMng", "povertyStrickenMng_street", {"id": id, "fatherId": fatherId, "operated": 0, "country": country, "village": village});
    });

    //导入功能
    importUpload("/poorFa/insert", getList, pageNo, pageSize);

    main.on('click', ".export_btn", function () { //导出功能
        //脱贫状态
        var povertyCheckbox = $("#poverty .povertyCheckbox");
        var povertyVal = [];
        $("#poverty .povertyCheckbox").each(function () {
            if ($(this).prop("checked")) {
                povertyVal.push($(this).val())
            }
        })
        location.href = "poorFa/exportPoorFamily?" + $("#searchForm").serialize() + "&poverty=" + povertyVal.join();
    })


    //进入编辑查看页面前，获取当前查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val(),
            prevFrom = {
                "cry": $('#cry').val(),
                "name": $('#name').val(),
                "year": $('#year').val(),
                "poverty": $('#poverty').val(),
                "attribute": $('#attribute').val(),
                "poorName": $('#poorName').val(),
                "idNumber": $('#idNumber').val(),
                "relation": $('#relation').val(),
                "employment": $('#employment option:selected').val()
            };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })

    getList(pageNo, pageSize)
}

/*嘉欣JavaScript end 0929*/

/*获取当前日期 strat*/
function nowDay() {
    var newDate = new Date();
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1;
    var day = newDate.getDate();
    var nowDay = year + '-' + month + '-' + day;
    return nowDay;
}

/*获取当前日期 end*/
/**
 * 截取图片文件名
 * Zeehol
 * @param filename
 * @returns string 文件名
 */
function clipImgName(filename) {
    var index = filename.lastIndexOf('_');
    return (index != -1) ? filename.substring(filename.lastIndexOf('_') + 1) : filename;
}

//bill 新增，输入框只能输入整数并保留小数点后两位
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        obj.value = parseFloat(obj.value);
    }
}

//bill 新增,js计算上年度自费金额
var costnum; //上年度医疗花费
var expensenum; //上年度医疗报销
var mynum;  //上年度自费金额
function calculate(obj) {
    clearNoNum(obj);
    costnum = $("#lastMedicalExpense").val();
    expensenum = $("#lastMedicalReimburse").val();
    illnum = $("#lastIllnessReimburse").val();
    mynum = costnum - expensenum - illnum;
    if (mynum < 0) {
        mynum = "";
        layer.msg("上年度医疗报销不能大于上年度医疗花费")
    }
    $("#lastSelfExpense").val(mynum)
}


/*cawiwen 一期重构 1102 start*/
function povertyStrickenEdit() {
    // 变量声明
    var id = mccms.getHash('id'), //贫困户id
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        operatedState = parseInt(mccms.getHash('operatedState')),
        detail = mccms.getHash('detail'),
        isEdit = mccms.getHash('isEdit'), //编辑状态
        addTime = sessionStorage.addTime, //使用H5本地储存获取时间
        familyArr = []; //存家庭成员数据

    var main = $('#MainList'),
        addMain = $('#addPopup'),
        modelForm = $('#modelForm'),
        memberArr = [],
        operated = 0,
        village1Id = null,
        size = 10,
        no = 1,
        pageCount = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //村的选中
        urlStr = "&cry=" + s_cry + "&name=" + s_name,
        // id ：操作记录的id
        // operated 0为返贫，1为脱贫

        getDetail = function (id) { //新增、查看、编辑方法 刷新页面

            /**
             *
             * 按照片属性名初始化上传照片功能
             * @param params  上传照片的属性数组
             */
            var fileInputCount = 0;

            function initImageUploaders(params) {
                for (var i = 0; i < params.length; i++) {
                    var fileInputId = params[i] + 'File';
                    var uploadedOpt = $('.' + params[i] + '-upload-pic-opt .uploaded-opt');
                    var unuploadedOpt = $('.' + params[i] + '-upload-pic-opt .unuploaded-opt');
                    var deleteButton = $('.' + params[i] + '-upload-pic-opt  .delete-btn');
                    var hiddenInput = $('#' + params[i]);
                    var uploadPicShow = $('.' + params[i] + '-upload-pic-opt .upload-pic-show');
                    uploadPicShow.html(clipImgName(hiddenInput.val()));

                    function bindFileInput(fileInputId, hiddenInput, uploadedOpt, unuploadedOpt, uploadPicShow) {
                        $("body").on('change', '#' + fileInputId, function () {//图片上传控件
                            $.ajaxFileUpload({
                                url: mccms.domain[0] + '/poorFa/poorFamilyImgUpload', //用于文件上传的服务器端请求地址
                                type: 'post',
                                secureuri: false, //是否需要安全协议，一般设置为false
                                fileElementId: fileInputId, //文件上传域的IDS
                                dataType: 'json',
                                success: function (data, xhr, jqXHR) //服务器成功响应处理函数
                                {
                                    if (data.status == "200") {
                                        var url = data.url;
                                        uploadPicShow.html(data.filename);
                                        hiddenInput.val(url);
                                        uploadedOpt.show();
                                        unuploadedOpt.hide();
                                        var fileInput = $('#' + fileInputId);
                                        fileInput.val('')
                                    } else {
                                        alert(data.message)
                                    }

                                },
                                error: function (data, status, e) //服务器响应失败处理函数
                                {
                                    alert(e)
                                }
                            });
                        });
                    }

                    bindFileInput(fileInputId, hiddenInput, uploadedOpt, unuploadedOpt, uploadPicShow);

                    (function (fileInputId, deleteButton, hiddenInput, uploadedOpt, unuploadedOpt) {
                        deleteButton.off('click');
                        deleteButton.on('click', function (e) {//删除按钮
                            e.preventDefault();
                            hiddenInput.val('');
                            uploadedOpt.hide();
                            unuploadedOpt.show();
                            var fileInput = $('#' + fileInputId);
                            fileInput.val('')
                        });
                    })(fileInputId, deleteButton, hiddenInput, uploadedOpt, unuploadedOpt);

                    (function (uploadPicShow, hiddenInput) {
                        uploadPicShow.off('click');
                        uploadPicShow.on('click', function (e) {//弹窗显示图片按钮
                            e.preventDefault();
                            var src = hiddenInput.val();
                            var img = new Image(); //图片预加载 获取宽高使layer居中
                            img.src = src;
                            img.onload = function () {
                                var w = img.width;
                                var h = img.height;
                                var layerw = 740;
                                var layerh = layerw / w * h + 35;
                                layerh = layerh > document.body.clientHeight ? document.body.clientHeight : layerh;
                                layer.open({
                                    title: uploadPicShow.html(),
                                    type: 1,
                                    area: [layerw + 'px', layerh + 'px'],
                                    content: '<img src="' + src + '" width="100%" />'
                                });
                            }
                        });
                    })(uploadPicShow, hiddenInput);
                }

            }

            if (!id) { //新增-页面
                //渲染主页面,但没填充数据
                mccms.getHbs({
                    "local": true,
                    "hbsName": "info",
                    "container": $("#addPopup"),
                    "data": {
                        operated: 1
                    },
                    "callback": function () {
                        /*收入、卫计、上年度收入信息-计算模块 start*/
                        //input  非空设置
                        $("#addPopup #div3 input").change(function () {
                            if ($(this).val() == '') {
                                $(this).val(0)
                            }
                        })

                        function incomeSum() { //纯收入计算
                            var year1 = parseFloat($("#year1").val()); //年收入
                            var expenses = parseFloat($("#expenses").val()); //生产性支出
                            $("#income").val((year1 - expenses).toFixed(2))
                        }

                        function perCapitaSum() { //人均纯收入计算
                            var familyNum = familyArr.length; //家庭成员数
                            familyNum == 0 ? familyNum = 1 : familyNum;
                            var income = parseFloat($("#income").val()); //纯收入
                            $("#perCapita").val((income / familyNum).toFixed(2))
                        }

                        //调用-计算
                        $("#planning,#low1,#five,#ecology").change(function () { //转移性收入
                            addMethod('tfSum', 'transfer'); //转移性收入
                            addMethod('yearSum', 'year1'); //年收入
                            incomeSum();
                            perCapitaSum();
                        });
                        $("#foodstuffAllowance,#captureIncome,#solatium,#otherTransfer").change(function () { //其他转移性收入
                            addMethod('elsesSum', 'elses');//其他转移性收入
                            addMethod('yearSum', 'year1'); //年收入
                            incomeSum();
                            perCapitaSum();
                        });
                        $("#wages,#operating,#property,#transfer,#elses").change(function () { //年收入
                            addMethod('yearSum', 'year1');//年收入
                            incomeSum();
                            perCapitaSum();
                        });
                        $("#year1,#expenses").change(function () { //纯收入
                            incomeSum();
                            perCapitaSum();
                        });
                        $("#income").change(function () { //人均纯收入
                            perCapitaSum();
                        });
                        /*收入、卫计、上年度收入信息-计算模块 end*/
                        /* 防贫信息 start*/
                        //申请时间
                        laydate.render({
                            elem: '#applicationTime',
                            type: 'datetime'
                        });
                        //查勘时间
                        laydate.render({
                            elem: '#reviewTime',
                            type: 'datetime'
                        });
                        //查勘结果时间
                        laydate.render({
                            elem: '#resultTime',
                            type: 'datetime'
                        });
                        //评议时间
                        laydate.render({
                            elem: '#evaluationTime',
                            type: 'datetime'
                        });
                        //公示时间
                        laydate.render({
                            elem: '#publicationTime',
                            type: 'datetime'
                        });

                        initImageUploaders(['reliefObjImg', 'evaluationTimeImg', 'publicationTimeImg', 'calamityImg', 'applicationTimeImg', 'educationImg', 'illnessImg', 'reliefAmoImg', 'resultContentImg']);
                        /* 防贫信息 end*/
                        /*帮扶措施模块 start*/

                        /*改变禁用与清空方法*/
                        function changeDis(sele, ipt1, ipt2, ipt3, ipt4) {
                            $("#" + sele).change(function () {
                                var valed = $("#" + sele).find("option:selected").val() //选定值
                                if (valed == '是') { //是
                                    $('#' + ipt1 + ',#' + ipt2 + ',#' + ipt3 + ',#' + ipt4).attr('disabled', false)
                                } else { //否
                                    $('#' + ipt1 + ',#' + ipt2 + ',#' + ipt3 + ',#' + ipt4).attr('disabled', true).val('')
                                }
                            })
                        }

                        changeDis('mifactory', 'miffactoryName', 'mifSalary', 'mifEmpName') //扶贫微工厂
                        changeDis('planTing', 'planName', 'planSubsidyAmo', 'planSales', 'planNickname') //种植业
                        changeDis('breed', 'breedName', 'breedSubsidyAmo', 'breedSales', 'breedNickname') //养殖业
                        changeDis('familyWork', 'famachinName', 'faIncome', 'faSales', 'faNickname')//家庭手工业
                        changeDis('phoStock', 'phoAnnInc', 'phoNickName') //光伏入股
                        changeDis('loan', 'loanMd', 'loan_Amo', 'loanTerm', 'loanPeople') //小额贷款
                        $("#shares").change(function () { //股份制
                            var valed = $("#shares").find("option:selected").val(); //选定值
                            if (valed == '设备入股') {
                                $("#equSbName, #equEnter, #equAmo, #equName").attr('disabled', false)
                                $("#capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', true).val('')
                            } else if (valed == '量资入股') {
                                $("#equSbName, #equEnter, #equAmo, #equName").attr('disabled', true).val('')
                                $("#capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', false)
                            } else { //其他
                                $("#equSbName, #equEnter, #equAmo, #equName, #capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', true).val('')
                            }
                        });
                        /*帮扶措施模块 end*/

                        modelForm = $('#modelForm');
                        modelForm.mcFormValide(); //绑定表单验证
                        getW();
                        //nav条定位锚点
                        scrollToBox("nav-item");
                        // //清空家庭成员列表
                        // mccms.ajax({ //新增时清空家庭成员列表API
                        //     "url": "/poorFa/deleteFamilyFid",
                        //     "cache": false,
                        //     "method": "POST"
                        // })

                        /*保存功能 start*/

                        function familySave() {
                            var family = {
                                dataid: new Date().getTime(),
                                name: $('#name1').val(),
                                number: $('#number').val(),
                                idType: $('#idType').val(),
                                birthTime: $('#birthTime').val(),
                                nation: $('#nation').val(),
                                culture: $('#culture').val(),
                                healthy: $('#healthy').val(),
                                soldier: $('#soldier').val(),
                                province: $('#province2').val(),
                                county: $('#county').val(),
                                workTime: $('#workTime').val(),
                                telephone: $('#telephone').val(),
                                enterTime: $('#enterTime').val(),
                                institution: $('#institution').val(),
                                county: $('#county2').val(),
                                sex: $('#sex').val(),
                                idNumber: $('#idNumber').val(),
                                relation: $('#relation').val(),
                                number: $('#number').val(),
                                political: $('#political').val(),
                                school: $('#school').val(),
                                labour: $('#labour').val(),
                                low: $('#low').val(),
                                city: $('#city2').val(),
                                village: $('#village2').val(),
                                company: $('#company').val(),
                                large: $('#large').val(),
                                schoolName: $('#schoolName').val(),
                                major: $('#major').val(),
                                isStudent: $('#isStudent').val(),
                                doType: $("#doType").val(),
                                medicalInsurance: $('#medicalInsurance').val(),
                                illness: $('#illness').val(),
                                illnessType: $('#illnessType').val(),
                                lastMedicalExpense: $('#lastMedicalExpense').val(),
                                lastMedicalReimburse: $('#lastMedicalReimburse').val(),
                                lastIllnessReimburse: $('#lastIllnessReimburse').val(),
                                lastSelfExpense: $('#lastSelfExpense').val(),
                                preventType: $('#preventType').val()
                            }
                            familyArr.push(family);

                        }

                        //家庭成员保存按钮触发询问框点击后的保存表单数据事件
                        function familySave2() {
                            var dataid = $("#dataid").attr("dataid")
                            if (dataid) { //编辑时
                                for (var i = 0; i < familyArr.length; i++) {
                                    if (familyArr[i].dataid == dataid) {
                                        var family = {
                                            dataid: dataid,
                                            name: $('#name1').val(),
                                            number: $('#number').val(),
                                            idType: $('#idType').val(),
                                            birthTime: $('#birthTime').val(),
                                            nation: $('#nation').val(),
                                            culture: $('#culture').val(),
                                            healthy: $('#healthy').val(),
                                            soldier: $('#soldier').val(),
                                            province: $('#province2').val(),
                                            county: $('#county').val(),
                                            workTime: $('#workTime').val(),
                                            telephone: $('#telephone').val(),
                                            enterTime: $('#enterTime').val(),
                                            institution: $('#institution').val(),
                                            county: $('#county2').val(),
                                            sex: $('#sex').val(),
                                            idNumber: $('#idNumber').val(),
                                            relation: $('#relation').val(),
                                            number: $('#number').val(),
                                            political: $('#political').val(),
                                            school: $('#school').val(),
                                            labour: $('#labour').val(),
                                            low: $('#low').val(),
                                            city: $('#city2').val(),
                                            village: $('#village2').val(),
                                            company: $('#company').val(),
                                            large: $('#large').val(),
                                            schoolName: $('#schoolName').val(),
                                            major: $('#major').val(),
                                            isStudent: $('#isStudent').val(),
                                            doType: $("#doType").val(),
                                            medicalInsurance: $('#medicalInsurance').val(),
                                            illness: $('#illness').val(),
                                            illnessType: $('#illnessType').val(),
                                            lastMedicalExpense: $('#lastMedicalExpense').val(),
                                            lastMedicalReimburse: $('#lastMedicalReimburse').val(),
                                            lastIllnessReimburse: $('#lastIllnessReimburse').val(),
                                            lastSelfExpense: $('#lastSelfExpense').val(),
                                            preventType: $('#preventType').val()
                                        }
                                        familyArr[i] = family;
                                    }
                                }
                            } else { //新增时
                                familySave()
                            }

                            //关闭弹窗
                            $("#addFamilyMask").hide();
                            $('#mainContainer').removeClass('noScroll')
                            //回显家庭成员列表
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "list",
                                "container": $("#tbody"),
                                "data": {result: familyArr},
                                "callback": function () {
                                    //家庭成员数改变后再次计算纯收入
                                    perCapitaSum()
                                }
                            });
                        }

                        //家庭成员保存按钮
                        $("#save1-btn").on("click", function () {
                            var Type = "因病"
                            if ($("#lastSelfExpense").val() >= 5000) {
                                layer.confirm('该户超过防贫预警线，是否启动防贫预警？', {
                                    btn: ['是', '否'] //按钮
                                }, function () {
                                    $('#preventType').val(Type)
                                    layer.msg("成功保存后将启动防贫预警")
                                    familySave2();
                                }, function () {
                                    $('#preventType').val("")
                                    layer.msg("不启动防贫预警")
                                    familySave2();
                                });
                            } else {
                                $('#preventType').val("")
                                familySave2();
                            }

                        })

                        /*保存功能 end*/

                        //家庭成员重置按钮
                        $("#modelForm .reset-btn").on("click", function () {
                            mccms.getHbs({ //家庭成员模板
                                "local": true,
                                "hbsName": "memberForm",
                                "container": $("#modelForm1"),
                                "data": {},
                                "callback": function () {
                                    laydate.render({ //出生日期
                                        elem: '#birthTime',
                                        max: nowDay()
                                    });
                                    laydate.render({ //入学时间
                                        elem: '#enterTime'
                                    });
                                }
                            })
                        })

                        //家庭成员新增按钮
                        $("#modelForm #addMember-btn").on("click", function () {
                            var checkboxMember = $('.checkbox-member input:checked')
                            if (checkboxMember.length) {
                                layer.msg('新增时不能勾选家庭成员')
                                return false
                            }
                            $("#addFamilyMask").show();
                            $('#mainContainer').addClass('noScroll');

                            mccms.getHbs({ //家庭成员弹窗
                                "local": true,
                                "hbsName": "memberForm",
                                "container": $("#modelForm1"),
                                "data": {},
                                "callback": function () {
                                    laydate.render({ //出生日期
                                        elem: '#birthTime',
                                        max: nowDay()
                                    });
                                    laydate.render({ //入学时间
                                        elem: '#enterTime'
                                    });

                                    //身份证读取
                                    function ClearIDCard() {
                                        CVR_IDCard.Name = "";
                                        CVR_IDCard.NameL = "";
                                        CVR_IDCard.Sex = "";
                                        CVR_IDCard.SexL = "";
                                        CVR_IDCard.Nation = "";
                                        //CVR_IDCard.NationL="";
                                        CVR_IDCard.Born = "";
                                        //CVR_IDCard.BornL="";
                                        CVR_IDCard.Address = "";
                                        CVR_IDCard.CardNo = "";
                                        CVR_IDCard.Police = "";
                                        CVR_IDCard.Activity = "";
                                        CVR_IDCard.NewAddr = "";

                                        return true;
                                    }

                                    function ReadIDCard() {
                                        CVR_IDCard.PhotoPath = 'C:\\'
                                        CVR_IDCard.TimeOut = 3;
                                        ClearIDCard();
                                        // return true;
                                    }

                                    $("#readyCard-btn").unbind("click");
                                    $('#readyCard-btn').on('click', function () {
                                        ReadIDCard()
                                        var State = CVR_IDCard.GetState;
                                        var strReadResult = CVR_IDCard.ReadCard;
                                        if (State !== '0') {
                                            layer.msg('请插入设备')
                                            return false
                                        }
                                        if (strReadResult !== '0') {
                                            layer.msg('请检查是否正常放置了身份证！')
                                            return false
                                        }
                                        if (CVR_IDCard.Sex === '1') {
                                            $('#sex').val('男')
                                        } else {
                                            $('#sex').val('女')
                                        }
                                        $('#name1').val(CVR_IDCard.NameL)
                                        $('#idNumber').val(CVR_IDCard.CardNo)
                                        $('#birthTime').val(CVR_IDCard.BornL)

                                        layer.msg('身份信息采集成功！', {
                                            icon: 1,
                                            shade: [0.8, '#000']
                                        })
                                    })

                                }
                            });
                        })

                        //家庭成员删除按钮
                        $('#deleteMember-btn').on('click', function () {
                            var checkboxMember = $('.checkbox-member input:checked')
                            if (!checkboxMember.length) {
                                layer.msg('请勾选家庭成员')
                                return false
                            }
                            var checkArr = []
                            checkboxMember.each(function (i, item) {
                                for (var j = 0; j < familyArr.length; j++) {
                                    if (familyArr[j].dataid == $(item).attr('dataid')) {
                                        familyArr.splice(j, 1)
                                    }
                                }
                            })

                            //回显家庭成员列表
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "list",
                                "container": $("#tbody"),
                                "data": {result: familyArr},
                                "callback": function () {
                                    console.log({result: familyArr})
                                    //家庭成员数改变后再次计算纯收入
                                    perCapitaSum()
                                }
                            })
                        })

                        //家庭成员编辑按钮
                        $('#modelForm #editMember-btn').on('click', function () {
                            $("#addFamilyMask #div1").text("编辑家庭成员")
                            var checkboxMember = $('.checkbox-member input:checked') //被勾选家庭成员
                            var familyMemberId = checkboxMember.attr("dataid"); //被勾选家庭成员dataid
                            if (!checkboxMember.length) {
                                layer.msg('请勾选家庭成员')
                                return false
                            }
                            if (checkboxMember.length > 1) {
                                layer.msg('只能单个修改')
                                return false
                            }
                            $("#addFamilyMask").show(); //家庭成员的弹窗
                            $('#mainContainer').addClass('noScroll');

                            for (var i = 0; i < familyArr.length; i++) {
                                if (familyArr[i].dataid == familyMemberId) {
                                    console.log(familyArr[i])
                                    mccms.getHbs({ //家庭成员弹窗
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": familyArr[i],
                                        "callback": function () {
                                            laydate.render({ //出生日期
                                                elem: '#birthTime',
                                                max: nowDay()
                                            });
                                            laydate.render({ //入学时间
                                                elem: '#enterTime'
                                            });

                                            //身份证读取
                                            function ClearIDCard() {
                                                CVR_IDCard.Name = "";
                                                CVR_IDCard.NameL = "";
                                                CVR_IDCard.Sex = "";
                                                CVR_IDCard.SexL = "";
                                                CVR_IDCard.Nation = "";
                                                //CVR_IDCard.NationL="";
                                                CVR_IDCard.Born = "";
                                                //CVR_IDCard.BornL="";
                                                CVR_IDCard.Address = "";
                                                CVR_IDCard.CardNo = "";
                                                CVR_IDCard.Police = "";
                                                CVR_IDCard.Activity = "";
                                                CVR_IDCard.NewAddr = "";

                                                return true;
                                            }

                                            function ReadIDCard() {
                                                CVR_IDCard.PhotoPath = 'C:\\'
                                                CVR_IDCard.TimeOut = 3;
                                                ClearIDCard();
                                                // return true;
                                            }

                                            $("#readyCard-btn").unbind("click");
                                            $('#readyCard-btn').on('click', function () {
                                                ReadIDCard()
                                                var State = CVR_IDCard.GetState;
                                                var strReadResult = CVR_IDCard.ReadCard;
                                                if (State !== '0') {
                                                    layer.msg('请插入设备')
                                                    return false
                                                }
                                                if (strReadResult !== '0') {
                                                    layer.msg('请检查是否正常放置了身份证！')
                                                    return false
                                                }
                                                if (CVR_IDCard.Sex === '1') {
                                                    $('#sex').val('男')
                                                } else {
                                                    $('#sex').val('女')
                                                }
                                                $('#name1').val(CVR_IDCard.NameL)
                                                $('#idNumber').val(CVR_IDCard.CardNo)
                                                $('#birthTime').val(CVR_IDCard.BornL)

                                                layer.msg('身份信息采集成功！', {
                                                    icon: 1,
                                                    shade: [0.8, '#000']
                                                })
                                            })
                                        }
                                    })
                                }
                            }


                            //请求单个家庭成员数据
                            mccms.ajax({ //查询单个家庭成员API
                                "url": "/poorFa/findFamily",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "sid": familyMemberId
                                },
                                success: function (data) {

                                }
                            })

                        })

                        //关闭弹窗
                        $('.close-btn').on('click', function () {
                            $("#addFamilyMask").hide();
                            $('#mainContainer').removeClass('noScroll')
                        })

                        /*-- 帮扶责任人模块 start --*/

                        //帮扶责任人新增按钮
                        $("#addPersons-btn").on("click", function () {
                            if ($("input[name='name']")) { //村级别时直接获取村的id
                                village1Id = $("#village1").find("option:selected").attr("id");
                            }
                            if (!village1Id) {
                                layer.msg("请选择行政村！");
                                return false;
                            }

                            layer.open({
                                type: 1,
                                title: "帮扶责任人结对信息",
                                area: ['80%', '60%'], //宽高
                                content: $("#jieduiPopup"),
                                success: function () {
                                    function searchFunc() { //帮扶责任人结对信息查询方法
                                        var unitName = $("#unitName").val(), //帮扶单位名称
                                            name = $("#name").val(), //姓名
                                            idNumber = $("#idNumber").val(); //证件号码
                                        mccms.ajax({ //村 查找对应 帮扶责任人结对信息API
                                            "url": "/helppeson/getHelpPersonByAreaId",
                                            "cache": false,
                                            "method": "POST",
                                            "data": "unitName=" + unitName + "&name=" + name + "&idNumber=" + idNumber + "&areaId=" + village1Id + "&pageNo=1" + "&pageSize=10",
                                            "success": function (data) {
                                                if (data.result) {
                                                    mccms.getHbs({
                                                        "local": true,
                                                        "hbsName": "addHelpList",
                                                        "container": $("#addHelpTobdy"),
                                                        "data": data,
                                                        "callback": function () {
                                                            mccms.pageHtml(data, getHelpPersonList, ''); //分页
                                                            //标记已选择的责任人
                                                            var personChecked = $("#helpTobdy input[name=help]"); //主页面-已选择责任人
                                                            var addPersonAll = $("#addHelpTobdy input[name=addHelp]"); //弹窗页面-所有责任人
                                                            personChecked.each(function (item) {
                                                                item = $(this).attr("id");
                                                                $('#addHelpTobdy input[id=' + item + ']').attr("checked", "checked")
                                                            })

                                                        }
                                                    });
                                                } else {
                                                    mccms.getHbs({
                                                        "local": true,
                                                        "hbsName": "addHelpList",
                                                        "container": $("#addHelpTobdy"),
                                                        "data": '',
                                                        "callback": function () {
                                                        }
                                                    });
                                                }
                                            }
                                        })
                                    }

                                    searchFunc()
                                    $(".query-btn").off().on("click", function () { //查询
                                        searchFunc()
                                    })

                                }

                            })
                        })
                        //帮扶责任人保存按钮
                        $("#keepPersons-btn").on("click", function () {

                            //帮扶责任人多选
                            var helpArr = $('#addHelpTobdy input[name=addHelp]:checked')
                            var arr1 = []; //帮扶责任人id数组
                            if (helpArr.length == 0) {
                                layer.msg("请先勾选帮扶责任人！")
                                return false
                            }
                            if (helpArr.length) {
                                helpArr.each(function (i, item) {
                                    arr1.push($(item).attr('id'))
                                })
                            }
                            layer.closeAll(); //关闭弹窗
                            var sid = arr1 ? arr1.join(',') : ''
                            getHelpPersonList(sid);

                        })
                        //帮扶责任人删除按钮
                        $("#deletePersons-btn").on("click", function () {
                            //帮扶责任人多选
                            var allHelpArr = $('#helpTobdy input[name=help]'); //所有责任人
                            var helpArr = allHelpArr.not(":checked"); //非选定状态责任人
                            var helpArred = $('#helpTobdy input[name=help]:checked'); //选定状态责任人
                            if (helpArred.length == 0) {
                                layer.msg("请先勾选帮扶责任人！")
                                return false
                            }
                            if (allHelpArr.length == 1 || allHelpArr.length == helpArred.length && helpArred) { //剩余一个责任人 或 删除全部时,清空表格
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "helpList",
                                    "container": $("#helpTobdy"),
                                    "data": '',
                                    "callback": function () {
                                        layer.msg("删除成功！")
                                    }
                                });

                            } else { //剩余多个责任人时
                                var arr1 = []; //责任人id数组
                                if (helpArr.length) {
                                    helpArr.each(function (i, item) {
                                        arr1.push($(item).attr('id'))
                                    })
                                }

                                var sid = arr1 ? arr1.join(',') : ''
                                getHelpPersonList(sid, true);
                            }
                        })
                        //帮扶责任人取消按钮
                        $("#cancelPersons-btn").on("click", function () {
                            layer.closeAll(); //关闭弹窗
                        })

                        /*-- 帮扶责任人模块 end -- */

                    }
                })
                //新增时隐藏 帮扶日志按钮
                $("#helpLog-btn").remove();

                return false;
            }
            //查看与编辑页面
            mccms.ajax({ //贫困户详情API - 参数: 贫困户id 
                "url": "/poorFa/getPoorFamily",
                "cache": false,
                "method": "POST",
                "data": {
                    "id": id
                },
                "success": function (data) {
                    // 改造填充数据
                    data.result.poorFamily.operated = operated
                    data.result.poorFamily.detail = detail
                    data.result.poorFamily.operatedState = operatedState; //operatedState==1为查看不可编辑,0为可编辑
                    data.result.poorFamily.edit = 1;

                    mccms.getHbs({ //填充表单
                        "local": true,
                        "hbsName": "info", //主模板
                        "container": $("#addPopup"), //主页面
                        "data": data.result,
                        "callback": function () {
                            //点位锚点
                            scrollToBox("nav-item")

                            //查看状态时,删除掉家庭成员的"新增、删除、编辑"三个按钮
                            if (data.result.poorFamily.operatedState == 1) {
                                $(".poverty-btnGroup").remove();
                                $("nav .c-primary").html("查看贫困户");
                            }
                            //修改模块名称-编辑
                            if (data.result.poorFamily.operatedState == 0) {
                                $("nav .c-primary").html("编辑贫困户");
                            }
                            //修改模块名称
                            if (inquire == 1) { //inquire == 1从《账表查询》过来则修改模块名称
                                $("nav .menuLevel1").html("账表查询");
                                $("nav .menuLevel2").html("贫困户查询");
                                $("nav .c-primary").html("查看贫困户");
                            }

                            /*收入、卫计、上年度收入信息-计算模块 start*/
                            //input  非空设置
                            $("#addPopup #div3 input").change(function () {
                                if ($(this).val() == '') {
                                    $(this).val(0)
                                }
                            })

                            function incomeSum() { //纯收入计算
                                var year1 = parseFloat($("#year1").val()); //年收入
                                var expenses = parseFloat($("#expenses").val()); //生产性支出
                                $("#income").val((year1 - expenses).toFixed(2))
                                perCapitaSum()
                            }

                            function perCapitaSum() { //人均纯收入计算
                                var familyNum = familyArr.length; //家庭成员数
                                familyNum == 0 ? familyNum = 1 : familyNum;
                                var income = parseFloat($("#income").val()); //纯收入
                                $("#perCapita").val((income / familyNum).toFixed(2))
                            }

                            //调用-计算
                            $("#planning,#low1,#five,#ecology").change(function () { //转移性收入
                                addMethod('tfSum', 'transfer') //转移性收入
                                addMethod('yearSum', 'year1') //年收入
                                incomeSum()
                                perCapitaSum()
                            })
                            $("#foodstuffAllowance,#captureIncome,#solatium,#otherTransfer").change(function () { //其他转移性收入
                                addMethod('elsesSum', 'elses') //其他转移性收入
                                addMethod('yearSum', 'year1') //年收入
                                incomeSum()
                                perCapitaSum()
                            })
                            $("#wages,#operating,#property,#transfer,#elses").change(function () { //年收入
                                addMethod('yearSum', 'year1') //年收入
                                incomeSum()
                                perCapitaSum()
                            })
                            $("#year1,#expenses").change(function () { //纯收入
                                incomeSum()
                                perCapitaSum()
                            })
                            $("#income").change(function () { //人均纯收入
                                perCapitaSum()
                            })
                            /*收入、卫计、上年度收入信息-计算模块 end*/

                            /* 防贫信息 start*/
                            //申请时间
                            laydate.render({
                                elem: '#applicationTime',
                                type: 'datetime'
                            })
                            //查勘时间
                            laydate.render({
                                elem: '#reviewTime',
                                type: 'datetime'
                            })
                            //查勘结果时间
                            laydate.render({
                                elem: '#resultTime',
                                type: 'datetime'
                            })
                            //评议时间
                            laydate.render({
                                elem: '#evaluationTime',
                                type: 'datetime'
                            })
                            //公示时间
                            laydate.render({
                                elem: '#publicationTime',
                                type: 'datetime'
                            })
                            initImageUploaders(['reliefObjImg', 'evaluationTimeImg', 'publicationTimeImg', 'calamityImg', 'applicationTimeImg', 'educationImg', 'illnessImg', 'reliefAmoImg', 'resultContentImg']);
                            /* 防贫信息 end*/

                            /*帮扶措施模块 start*/

                            /*改变禁用与清空方法*/
                            function changeDis(sele, ipt1, ipt2, ipt3, ipt4) {
                                $("#" + sele).change(function () {
                                    var valed = $("#" + sele).find("option:selected").val() //选定值

                                    if (valed == '是') { //是
                                        $('#' + ipt1 + ',#' + ipt2 + ',#' + ipt3 + ',#' + ipt4).attr('disabled', false)
                                    } else { //否
                                        $('#' + ipt1 + ',#' + ipt2 + ',#' + ipt3 + ',#' + ipt4).attr('disabled', true).val('')
                                    }
                                })
                            }

                            changeDis('mifactory', 'miffactoryName', 'mifSalary', 'mifEmpName') //扶贫微工厂
                            changeDis('planTing', 'planName', 'planSubsidyAmo', 'planSales', 'planNickname') //种植业
                            changeDis('breed', 'breedName', 'breedSubsidyAmo', 'breedSales', 'breedNickname') //养殖业
                            changeDis('familyWork', 'famachinName', 'faIncome', 'faSales', 'faNickname')//家庭手工业
                            changeDis('phoStock', 'phoAnnInc', 'phoNickName') //光伏入股
                            changeDis('loan', 'loanMd', 'loan_Amo', 'loanTerm', 'loanPeople') //小额贷款

                            $("#shares").change(function () { //股份制
                                var valed = $("#shares").find("option:selected").val(); //选定值
                                if (valed == '设备入股') {
                                    $("#equSbName, #equEnter, #equAmo, #equName").attr('disabled', false)
                                    $("#capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', true).val('')
                                } else if (valed == '量资入股') {
                                    $("#equSbName, #equEnter, #equAmo, #equName").attr('disabled', true).val('')
                                    $("#capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', false)
                                } else { //其他
                                    $("#equSbName, #equEnter, #equAmo, #equName, #capAmo, #capEnter, #capBomAmo, #capName").attr('disabled', true).val('')
                                }
                            })
                            /*帮扶措施模块 end*/
                            //填充省市区乡村值
                            getW({
                                province: data.result.poorFamily.province,
                                city: data.result.poorFamily.city,
                                county: data.result.poorFamily.county,
                                country: data.result.poorFamily.country,
                                village: data.result.poorFamily.village
                            })

                            //填充其他致贫原因
                            var otherArr = data.result.poorFamily.other ? data.result.poorFamily.other.split(',') : ''
                            if (otherArr) {
                                for (var i = 0; i < otherArr.length; i++) {
                                    $('#other input').each(function (j, item) {
                                        if (item.value === otherArr[i]) {
                                            $(item).prop('checked', true)
                                        }
                                    })
                                }
                            }

                            modelForm = $('#modelForm'); //主模板表单
                            modelForm.mcFormValide(); //绑定表单验证

                            if (operatedState == 1) { //查看页面时
                                //填充家庭成员列表
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "list",
                                    "container": $("#tbody"),
                                    "data": {
                                        result: data.result.poorFamily.family
                                    }
                                })
                            }

                            //新增、删除、编辑按钮组
                            if (isEdit) { //isEdit==1表示编辑页面
                                var oldFamily = data.result.poorFamily.family; //贫困户原本家庭成员
                                for (var i = 0; i < oldFamily.length; i++) {
                                    oldFamily[i].dataid = oldFamily[i].id
                                }
                                familyArr = oldFamily.concat(familyArr) //合并家庭成员
                                //填充家庭成员列表
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "list",
                                    "container": $("#tbody"),
                                    "data": {
                                        result: familyArr
                                    }
                                    , "callback": function () {
                                        console.log(familyArr)
                                    }
                                })

                                /*保存功能 start*/
                                function familySave() {
                                    var family = {
                                        dataid: new Date().getTime(),
                                        name: $('#name1').val(),
                                        number: $('#number').val(),
                                        idType: $('#idType').val(),
                                        birthTime: $('#birthTime').val(),
                                        nation: $('#nation').val(),
                                        culture: $('#culture').val(),
                                        healthy: $('#healthy').val(),
                                        soldier: $('#soldier').val(),
                                        province: $('#province2').val(),
                                        county: $('#county').val(),
                                        workTime: $('#workTime').val(),
                                        telephone: $('#telephone').val(),
                                        enterTime: $('#enterTime').val(),
                                        institution: $('#institution').val(),
                                        county: $('#county2').val(),
                                        sex: $('#sex').val(),
                                        idNumber: $('#idNumber').val(),
                                        relation: $('#relation').val(),
                                        number: $('#number').val(),
                                        political: $('#political').val(),
                                        school: $('#school').val(),
                                        labour: $('#labour').val(),
                                        low: $('#low').val(),
                                        city: $('#city2').val(),
                                        village: $('#village2').val(),
                                        company: $('#company').val(),
                                        large: $('#large').val(),
                                        schoolName: $('#schoolName').val(),
                                        major: $('#major').val(),
                                        isStudent: $('#isStudent').val(),
                                        doType: $("#doType").val(),
                                        medicalInsurance: $('#medicalInsurance').val(),
                                        illness: $('#illness').val(),
                                        illnessType: $('#illnessType').val(),
                                        lastMedicalExpense: $('#lastMedicalExpense').val(),
                                        lastMedicalReimburse: $('#lastMedicalReimburse').val(),
                                        lastIllnessReimburse: $('#lastIllnessReimburse').val(),
                                        lastSelfExpense: $('#lastSelfExpense').val(),
                                        preventType: $('#preventType').val()
                                    }
                                    familyArr.push(family)
                                }

                                //家庭成员保存按钮触发询问框点击后的保存表单数据事件
                                function familySave3() {
                                    var dataid = $("#dataid").attr("dataid")
                                    if (dataid) { //编辑时
                                        for (var i = 0; i < familyArr.length; i++) {
                                            if (familyArr[i].dataid == dataid) {
                                                var familyId = familyArr[i].id; //家庭成员id
                                                var addTime = familyArr[i].addTime; //添加时间
                                                var annual = familyArr[i].annual; //数据年度

                                                var family = {
                                                    id: familyId,
                                                    addTime: addTime,
                                                    annual: annual,
                                                    dataid: dataid,
                                                    name: $('#name1').val(),
                                                    number: $('#number').val(),
                                                    idType: $('#idType').val(),
                                                    birthTime: $('#birthTime').val(),
                                                    nation: $('#nation').val(),
                                                    culture: $('#culture').val(),
                                                    healthy: $('#healthy').val(),
                                                    soldier: $('#soldier').val(),
                                                    province: $('#province2').val(),
                                                    county: $('#county').val(),
                                                    workTime: $('#workTime').val(),
                                                    telephone: $('#telephone').val(),
                                                    enterTime: $('#enterTime').val(),
                                                    institution: $('#institution').val(),
                                                    county: $('#county2').val(),
                                                    sex: $('#sex').val(),
                                                    idNumber: $('#idNumber').val(),
                                                    relation: $('#relation').val(),
                                                    number: $('#number').val(),
                                                    political: $('#political').val(),
                                                    school: $('#school').val(),
                                                    labour: $('#labour').val(),
                                                    low: $('#low').val(),
                                                    city: $('#city2').val(),
                                                    village: $('#village2').val(),
                                                    company: $('#company').val(),
                                                    large: $('#large').val(),
                                                    schoolName: $('#schoolName').val(),
                                                    major: $('#major').val(),
                                                    isStudent: $('#isStudent').val(),
                                                    doType: $("#doType").val(),
                                                    medicalInsurance: $('#medicalInsurance').val(),
                                                    illness: $('#illness').val(),
                                                    illnessType: $('#illnessType').val(),
                                                    lastMedicalExpense: $('#lastMedicalExpense').val(),
                                                    lastMedicalReimburse: $('#lastMedicalReimburse').val(),
                                                    lastIllnessReimburse: $('#lastIllnessReimburse').val(),
                                                    lastSelfExpense: $('#lastSelfExpense').val(),
                                                    preventType: $('#preventType').val()
                                                }
                                                familyArr[i] = family;

                                            }
                                        }
                                    } else { //新增时
                                        familySave()
                                    }


                                    //关闭弹窗
                                    $("#addFamilyMask").hide();
                                    $('#mainContainer').removeClass('noScroll')


                                    //回显家庭成员列表
                                    mccms.getHbs({
                                        "local": true,
                                        "hbsName": "list",
                                        "container": $("#tbody"),
                                        "data": {result: familyArr},
                                        "callback": function () {
                                            //家庭成员数改变后再次计算纯收入
                                            perCapitaSum()
                                        }
                                    });
                                }

                                //家庭成员保存按钮
                                $("#save1-btn").on("click", function () {
                                    var Type = "因病"
                                    if ($("#lastSelfExpense").val() >= 5000) {
                                        layer.confirm('该户超过防贫预警线，是否启动防贫预警？', {
                                            btn: ['是', '否'] //按钮
                                        }, function () {
                                            $('#preventType').val(Type)
                                            layer.msg("成功保存后将启动防贫预警")
                                            familySave3();
                                        }, function () {
                                            $('#preventType').val("")
                                            layer.msg("不启动防贫预警")
                                            familySave3();
                                        });
                                    } else {
                                        $('#preventType').val("")
                                        familySave3();
                                    }

                                })

                                /*保存功能 end*/


                                //家庭成员重置按钮
                                $("#modelForm .reset-btn").on("click", function () {
                                    mccms.getHbs({ //家庭成员模板
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": {}
                                    })
                                })

                                //家庭成员新增按钮
                                $("#modelForm #addMember-btn").on("click", function () {
                                    var checkboxMember = $('.checkbox-member input:checked')
                                    if (checkboxMember.length) {
                                        layer.msg('新增时不能勾选家庭成员')
                                        return false
                                    }
                                    $("#addFamilyMask").show();
                                    $('#mainContainer').addClass('noScroll');

                                    mccms.getHbs({ //家庭成员弹窗
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": {},
                                        "callback": function () {
                                            laydate.render({ //出生日期
                                                elem: '#birthTime',
                                                max: nowDay()
                                            });
                                            laydate.render({ //入学时间
                                                elem: '#enterTime'
                                            });

                                            //身份证读取
                                            function ClearIDCard() {
                                                CVR_IDCard.Name = "";
                                                CVR_IDCard.NameL = "";
                                                CVR_IDCard.Sex = "";
                                                CVR_IDCard.SexL = "";
                                                CVR_IDCard.Nation = "";
                                                //CVR_IDCard.NationL="";
                                                CVR_IDCard.Born = "";
                                                //CVR_IDCard.BornL="";
                                                CVR_IDCard.Address = "";
                                                CVR_IDCard.CardNo = "";
                                                CVR_IDCard.Police = "";
                                                CVR_IDCard.Activity = "";
                                                CVR_IDCard.NewAddr = "";

                                                return true;
                                            }

                                            function ReadIDCard() {
                                                CVR_IDCard.PhotoPath = 'C:\\'
                                                CVR_IDCard.TimeOut = 3;
                                                ClearIDCard();
                                                // return true;
                                            }

                                            $("#readyCard-btn").unbind("click");
                                            $('#readyCard-btn').on('click', function () {
                                                ReadIDCard()
                                                var State = CVR_IDCard.GetState;
                                                var strReadResult = CVR_IDCard.ReadCard;
                                                if (State !== '0') {
                                                    layer.msg('请插入设备')
                                                    return false
                                                }
                                                if (strReadResult !== '0') {
                                                    layer.msg('请检查是否正常放置了身份证！')
                                                    return false
                                                }
                                                if (CVR_IDCard.Sex === '1') {
                                                    $('#sex').val('男')
                                                } else {
                                                    $('#sex').val('女')
                                                }
                                                $('#name1').val(CVR_IDCard.NameL)
                                                $('#idNumber').val(CVR_IDCard.CardNo)
                                                $('#birthTime').val(CVR_IDCard.BornL)

                                                layer.msg('身份信息采集成功！', {
                                                    icon: 1,
                                                    shade: [0.8, '#000']
                                                })
                                            })
                                        }
                                    });
                                })

                                //家庭成员删除按钮
                                $('#deleteMember-btn').on('click', function () {
                                    var checkboxMember = $('.checkbox-member input:checked')
                                    if (!checkboxMember.length) {
                                        layer.msg('请勾选家庭成员')
                                        return false
                                    }
                                    var checkArr = []
                                    checkboxMember.each(function (i, item) {
                                        for (var j = 0; j < familyArr.length; j++) {
                                            if (familyArr[j].dataid == $(item).attr('dataid')) {
                                                familyArr.splice(j, 1)
                                            }
                                        }
                                    })

                                    //回显家庭成员列表
                                    mccms.getHbs({
                                        "local": true,
                                        "hbsName": "list",
                                        "container": $("#tbody"),
                                        "data": {result: familyArr},
                                        "callback": function () {
                                            //家庭成员数改变后再次计算纯收入
                                            perCapitaSum()
                                        }
                                    })
                                })

                                //家庭成员编辑按钮
                                $('#modelForm #editMember-btn').on('click', function () {
                                    $("#addFamilyMask #div1").text("编辑家庭成员")
                                    var checkboxMember = $('.checkbox-member input:checked') //被勾选家庭成员
                                    var familyMemberId = checkboxMember.attr("dataid"); //被勾选家庭成员dataid
                                    if (!checkboxMember.length) {
                                        layer.msg('请勾选家庭成员')
                                        return false
                                    }
                                    if (checkboxMember.length > 1) {
                                        layer.msg('只能单个修改')
                                        return false
                                    }
                                    $("#addFamilyMask").show(); //家庭成员的弹窗
                                    $('#mainContainer').addClass('noScroll');

                                    for (var i = 0; i < familyArr.length; i++) {

                                        if (familyArr[i].dataid == familyMemberId) {
                                            var onCheckFamily = familyArr[i];
                                            mccms.getHbs({ //家庭成员弹窗
                                                "local": true,
                                                "hbsName": "memberForm",
                                                "container": $("#modelForm1"),
                                                "data": familyArr[i],
                                                "callback": function () {
                                                    laydate.render({ //出生日期
                                                        elem: '#birthTime',
                                                        max: nowDay()
                                                    });
                                                    laydate.render({ //入学时间
                                                        elem: '#enterTime'
                                                    });

                                                    //身份证读取
                                                    function ClearIDCard() {
                                                        CVR_IDCard.Name = "";
                                                        CVR_IDCard.NameL = "";
                                                        CVR_IDCard.Sex = "";
                                                        CVR_IDCard.SexL = "";
                                                        CVR_IDCard.Nation = "";
                                                        //CVR_IDCard.NationL="";
                                                        CVR_IDCard.Born = "";
                                                        //CVR_IDCard.BornL="";
                                                        CVR_IDCard.Address = "";
                                                        CVR_IDCard.CardNo = "";
                                                        CVR_IDCard.Police = "";
                                                        CVR_IDCard.Activity = "";
                                                        CVR_IDCard.NewAddr = "";

                                                        return true;
                                                    }

                                                    function ReadIDCard() {
                                                        CVR_IDCard.PhotoPath = 'C:\\'
                                                        CVR_IDCard.TimeOut = 3;
                                                        ClearIDCard();
                                                        // return true;
                                                    }

                                                    function editData() {
                                                        if (CVR_IDCard.Sex === '1') {
                                                            $('#sex').val('男')
                                                        } else {
                                                            $('#sex').val('女')
                                                        }
                                                        $('#name1').val(CVR_IDCard.NameL)
                                                        $('#idNumber').val(CVR_IDCard.CardNo)
                                                        $('#birthTime').val(CVR_IDCard.BornL)
                                                    }

                                                    $("#readyCard-btn").unbind("click");
                                                    $('#readyCard-btn').on('click', function () {
                                                        ReadIDCard()
                                                        var State = CVR_IDCard.GetState;
                                                        var strReadResult = CVR_IDCard.ReadCard;
                                                        if (State !== '0') {
                                                            layer.msg('请插入设备')
                                                            return false
                                                        }
                                                        if (strReadResult !== '0') {
                                                            layer.msg('请检查是否正常放置了身份证！')
                                                            return false
                                                        }


                                                        //核对验证
                                                        function checkFamily() {
                                                            if (onCheckFamily.name === CVR_IDCard.NameL
                                                                && onCheckFamily.idNumber === CVR_IDCard.CardNo
                                                                && onCheckFamily.birthTime === CVR_IDCard.BornL
                                                                && onCheckFamily.sex === (CVR_IDCard.Sex === '1' ? '男' : '女')) {
                                                                layer.msg('身份信息核对一致！', {
                                                                    icon: 1,
                                                                    area: ['400px', '70px'],
                                                                    shade: [0.8, '#000']
                                                                })

                                                            } else {
                                                                layer.msg('身份信息核对不一致，系统将会自动修正数据！', {
                                                                    icon: 2,
                                                                    area: ['400px', '70px'],
                                                                    shade: [0.8, '#000']
                                                                })
                                                            }
                                                            editData()

                                                        }

                                                        checkFamily()


                                                    })


                                                }
                                            })
                                        }

                                    }

                                })

                                //关闭弹窗
                                $('.close-btn').on('click', function () {
                                    $("#addFamilyMask").hide();
                                    $('#mainContainer').removeClass('noScroll')
                                })

                                /*帮扶责任人模块 start*/
                                //帮扶责任人新增按钮
                                $("#addPersons-btn").on("click", function () {
                                    if ($("input[name='name']")) { //村级别时直接获取村的id
                                        village1Id = $("#village1").find("option:selected").attr("id");
                                    }
                                    if (!village1Id) {
                                        layer.msg("请先填写家庭住址！");
                                        return false;
                                    }
                                    layer.open({
                                        type: 1,
                                        title: "帮扶责任人结对信息",
                                        area: ['80%', '60%'], //宽高
                                        content: $("#jieduiPopup"),
                                        success: function () {
                                            function searchFunc() { //帮扶责任人结对信息查询方法
                                                var unitName = $("#unitName").val(), //帮扶单位名称
                                                    name = $("#name").val(), //姓名
                                                    idNumber = $("#idNumber").val(); //证件号码
                                                mccms.ajax({ //村 查找对应 帮扶责任人结对信息API
                                                    "url": "/helppeson/getHelpPersonByAreaId",
                                                    "cache": false,
                                                    "method": "POST",
                                                    "data": "unitName=" + unitName + "&name=" + name + "&idNumber=" + idNumber + "&areaId=" + village1Id + "&pageNo=1" + "&pageSize=10",
                                                    "success": function (data) {
                                                        if (data.result) {
                                                            mccms.getHbs({
                                                                "local": true,
                                                                "hbsName": "addHelpList",
                                                                "container": $("#addHelpTobdy"),
                                                                "data": data,
                                                                "callback": function () {
                                                                    mccms.pageHtml(data, getHelpPersonList, ''); //分页
                                                                    //标记已选择的责任人
                                                                    var personChecked = $("#helpTobdy input[name=help]"); //主页面-已选择责任人
                                                                    var addPersonAll = $("#addHelpTobdy input[name=addHelp]"); //弹窗页面-所有责任人
                                                                    personChecked.each(function (item) {
                                                                        item = $(this).attr("id");
                                                                        $('#addHelpTobdy input[id=' + item + ']').attr("checked", "checked")
                                                                    })

                                                                }
                                                            });
                                                        } else {
                                                            mccms.getHbs({
                                                                "local": true,
                                                                "hbsName": "addHelpList",
                                                                "container": $("#addHelpTobdy"),
                                                                "data": '',
                                                                "callback": function () {
                                                                }
                                                            });
                                                        }
                                                    }
                                                })
                                            }

                                            searchFunc()
                                            $(".query-btn").off().on("click", function () { //查询
                                                searchFunc()
                                            })

                                        }
                                    })
                                })
                                //帮扶责任人保存按钮
                                $("#keepPersons-btn").on("click", function () {

                                    //帮扶责任人多选
                                    var helpArr = $('#addHelpTobdy input[name=addHelp]:checked')
                                    var arr1 = []; //帮扶责任人id数组
                                    if (helpArr.length == 0) {
                                        layer.msg("请先勾选帮扶责任人！")
                                        return false
                                    }
                                    if (helpArr.length) {
                                        helpArr.each(function (i, item) {
                                            arr1.push($(item).attr('id'))
                                        })
                                    }
                                    layer.closeAll(); //关闭弹窗
                                    var sid = arr1 ? arr1.join(',') : ''
                                    getHelpPersonList(sid);

                                })
                                //帮扶责任人删除按钮
                                $("#deletePersons-btn").on("click", function () {
                                    //帮扶责任人多选
                                    var allHelpArr = $('#helpTobdy input[name=help]'); //所有责任人
                                    var helpArr = allHelpArr.not(":checked"); //非选定状态责任人
                                    var helpArred = $('#helpTobdy input[name=help]:checked'); //选定状态责任人
                                    if (helpArred.length == 0) {
                                        layer.msg('请先勾选帮扶责任人！')
                                        return false
                                    }
                                    if (allHelpArr.length == 1 || allHelpArr.length == helpArred.length && helpArred) { //剩余一个责任人 或 删除全部时,清空表格
                                        mccms.getHbs({
                                            "local": true,
                                            "hbsName": "helpList",
                                            "container": $("#helpTobdy"),
                                            "data": '',
                                            "callback": function () {
                                                layer.msg("删除成功！")
                                            }
                                        });

                                    } else {
                                        //剩余多个责任人时
                                        var arr1 = []; //责任人id数组
                                        if (helpArr.length) {
                                            helpArr.each(function (i, item) {
                                                arr1.push($(item).attr('id'))
                                            })
                                        }

                                        var sid = arr1 ? arr1.join(',') : ''
                                        getHelpPersonList(sid, true);

                                    }

                                })

                                //帮扶责任人取消按钮
                                $("#cancelPersons-btn").on("click", function () {
                                    layer.closeAll(); //关闭弹窗
                                })

                                /*帮扶责任人模块 end*/


                            }
                            //帮扶责任人结对信息回显
                            if (detail && !operated) {
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "helpList",
                                    "container": $("#helpTobdy"),
                                    "data": {
                                        result: data.result.poorFamily.helpPersons
                                    },
                                    "callback": function () {
                                    }
                                });
                            }


                        }
                    });
                }
            })


        },
        getMemberList = function (id) { //家庭成员列表
            var familyUrl = id ? "/poorFa/getPoorFamily" : "/poorFa/queryFamily"; //前者表示编辑页面时API，后者表示新增页面时API
            var familyData = id ? {"id": id} : ""; //前者表示编辑页面时参数-用户id，后者表示新增页面时 参数
            mccms.ajax({ //贫困户详情API - 参数: 贫困户id  
                "url": familyUrl,
                "cache": false,
                "method": "POST",
                "data": familyData,
                "success": function (data) {
                    var resultData; //填充的数据
                    if (id) { //编辑页面时
                        data.result.poorFamily.family.forEach(function (item) { //所有家庭成员的id,用于保存到对应贫困户里
                            memberArr.push(item.id)
                        })
                        resultData = {result: data.result.poorFamily.family};
                    } else { //新增页面时
                        data.result.forEach(function (item) {
                            memberArr.push(item.id)
                        })
                        resultData = {result: data.result};
                    }

                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": resultData,
                        "callback": function () {
                        }
                    });
                }
            })
        },
        getHelpPersonList = function (sid, del) { //回显帮扶责任人结对信息
            mccms.ajax({ //通过责任人id数组查找帮扶责任人API
                "url": '/helppeson/findhelppesonMultiple',
                "cache": false,
                "method": "POST",
                "data": {sid: sid},
                "success": function (data) {
                    if (data.result) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "helpList",
                            "container": $("#helpTobdy"),
                            "data": data,
                            "callback": function () {
                                if (del) {
                                    layer.msg("删除成功！")
                                } else {
                                    layer.msg("新增成功！")
                                }
                                mccms.pageHtml(data, getHelpPersonList, '');
                            }
                        });
                    } else {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "helpList",
                            "container": $("#helpTobdy"),
                            "data": '',
                            "callback": function () {
                            }
                        });
                    }
                }
            })
        },
        subMemberMsg = function () { //家庭成员保存
            var data1 = {
                name: $('#name1').val(),
                number: $('#number').val(),
                idType: $('#idType').val(),
                birthTime: $('#birthTime').val(),
                nation: $('#nation').val(),
                culture: $('#culture').val(),
                healthy: $('#healthy').val(),
                soldier: $('#soldier').val(),
                province: $('#province2').val(),
                county: $('#county').val(),
                workTime: $('#workTime').val(),
                telephone: $('#telephone').val(),
                enterTime: $('#enterTime').val(),
                institution: $('#institution').val(),
                county: $('#county2').val(),
                sex: $('#sex').val(),
                idNumber: $('#idNumber').val(),
                relation: $('#relation').val(),
                number: $('#number').val(),
                political: $('#political').val(),
                school: $('#school').val(),
                labour: $('#labour').val(),
                low: $('#low').val(),
                city: $('#city2').val(),
                village: $('#village2').val(),
                company: $('#company').val(),
                large: $('#large').val(),
                schoolName: $('#schoolName').val(),
                major: $('#major').val(),
                isStudent: $('#isStudent').val(),
                doType: $("#doType").val()
            }
            if (id) {
                data1.fid = mccms.getHash('id'); //用户id
            }

            var checkboxMember = $('.checkbox-member input:checked') //选定的家庭成员
            if (checkboxMember.length >= 2) {
                layer.msg('只能单个修改')
                return false
            } else if (checkboxMember.length === 1) { //编辑保存时

                data1.id = checkboxMember.attr('id'); //家庭成员id
                data1.fid = checkboxMember.attr('attr-fid'); //贫困户id

                mccms.ajax({ //修改家庭成员API - 参数: 贫困户id
                    "url": "/poorFa/addOrUpdateFamily",
                    "cache": false,
                    "method": "POST",
                    "data": data1,
                    "success": function () {
                        var id = mccms.getHash('id'); //用户id
                        mccms.ajax({ //查询家庭成员API
                            "url": "/poorFa/getPoorFamily",
                            "cache": false,
                            "method": "POST",
                            "data": data1,
                            "success": function (data) {
                                $("#addFamilyMask").hide();
                                $('#mainContainer').removeClass('noScroll')

                                if (!id) { //刷新 -- 新增页面-编辑
                                    var familyM = $("#tbody input[type=checkbox]"); //家庭成员
                                    var familySid = []; //家庭成员id数组
                                    familyM.each(function () {
                                        familySid.push($(this).attr("id"))
                                    })
                                    familySid = familySid.join(",")

                                    mccms.ajax({ //家庭成员详情API - 参数sid: 家庭成员id数组  
                                        "url": "/poorFa/findFamily",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            "sid": familySid
                                        },
                                        "success": function (data) {
                                            mccms.getHbs({
                                                "local": true,
                                                "hbsName": "list",
                                                "container": $("#tbody"),
                                                "data": data,
                                                "callback": function () {
                                                }
                                            });
                                        }
                                    })
                                } else { //刷新 -- 编辑页面-编辑
                                    getMemberList(id)
                                }

                            }
                        })
                    }
                })
            } else { //新增按钮-保存
                var addUrl = id ? "/poorFa/addOrUpdateFamily" : "/poorFa/addFamily"; //前者编辑页面时的新增按钮，后者新增页面时的新增按钮
                mccms.ajax({ //新增与修改家庭成员API - 参数: 贫困户id
                    "url": addUrl,
                    "cache": false,
                    "method": "POST",
                    "data": data1,
                    "success": function () {
                        //关闭弹窗
                        $("#addFamilyMask").hide();
                        $('#mainContainer').removeClass('noScroll')

                        //家庭成员列表刷新
                        getMemberList(id)
                    }
                })
            }
        },
        subMsg = function () { //保存贫困户
            //其他贫困原因多选
            var arr = []
            var otherArr = $('#other input:checked')
            for (var i = 0; i < otherArr.length; i++) {
                arr.push(otherArr[i].value)
            }

            //帮扶责任人多选
            var helpArr = $('#helpTobdy input[name=help]')
            var arr1 = []
            if (helpArr.length) {
                helpArr.each(function (i, item) {
                    arr1.push($(item).attr('id'))
                })
            }

            var valid = modelForm.valid();
            var data = {
                province: $('#province1').val(),
                city: $('#city1').val(),
                county: $('#county').val(),
                country: $('#country').val(),
                village: $('#village1').val(),
                number: $('#number1').val(),
                contact: $('#contact').val(),
                bank: $('#bank').val(),
                cardNumber: $('#cardNumber').val(),
                standard: $('#standard').val(),
                poverty: $('#poverty').val(),
                attribute: $('#attribute').val(),
                soldier: $('#soldier1').val(),
                vehicle: $('#vehicle').val(),
                room: $('#room').val(),
                company: $('#company1').val(),
                reason: $('#reason input:checked').val() ? $('#reason input:checked').val() : '',
                other: arr.join(','),
                cuedLand: $('#cuedLand').val(),
                irrigation: $('#irrigation').val(),
                woodLand: $('#woodLand').val(),
                farmLand: $('#farmLand').val(),
                fruit: $('#fruit').val(),
                forageGrass: $('#forageGrass').val(),
                waters: $('#waters').val(),
                production: $('#production').val(),
                cooperative: $('#cooperative').val(),
                distance: $('#distance').val(),
                type: $('#type').val(),
                housing: $('#housing').val(),
                life: $('#life').val(),
                difficulty: $('#difficulty').val(),
                security: $('#security').val(),
                danger: $('#danger').val(),
                level: $('#level').val(),
                fuel: $('#fuel').val(),
                toilet: $('#toilet').val(),
                //收入、卫计、上年度收入信息 start
                wages: $('#wages').val(),
                operating: $('#operating').val(),
                property: $('#property').val(),
                transfer: $('#transfer').val(),
                planning: $('#planning').val(),
                low: $('#low1').val(),
                five: $('#five').val(),
                pension: $('#pension').val(),
                ecology: $('#ecology').val(),
                elses: $('#elses').val(),
                year: $('#year1').val(),
                expenses: $('#expenses').val(),
                income: $('#income').val(),
                perCapita: $('#perCapita').val(),
                alone: $('#alone').val(),
                twoGirl: $('#twoGirl').val(),
                foodstuffAllowance: $('#foodstuffAllowance').val(), //粮食直补
                captureIncome: $('#captureIncome').val(), //非常住人员寄回带回收入
                solatium: $('#solatium').val(), //赡养费
                otherTransfer: $('#otherTransfer').val(), //其他//（其他转移性收入中的其他）
                //收入、卫计、上年度收入信息 end
                // familys: JSON.stringify(memberArr),
                persons: arr1 ? arr1.join(',') : '', //帮扶责任人id
                familys: JSON.stringify(familyArr), //家庭成员

                //以下防贫信息
                preventAttribute: $('#preventAttribute').val(),
                reliefObj: $('#reliefObj').val(),
                reliefObjImg: $('#reliefObjImg').val(),
                preventReason: $('#preventReason').val(),
                applicationTime: $('#applicationTime').val(),
                applicationTimeImg: $('#applicationTimeImg').val(),
                reviewTime: $('#reviewTime').val(),

                resultTime: $('#resultTime').val(),
                resultContent: $('#resultContent').val(),
                resultContentImg: $('#resultContentImg').val(),
                reviewConclusion: $('#reviewConclusion').val(),
                verifier: $('#verifier').val(),
                evaluationTime: $('#evaluationTime').val(),
                evaluationTimeImg: $('#evaluationTimeImg').val(),

                publicationTime: $('#publicationTime').val(),
                publicationTimeImg: $('#publicationTimeImg').val(),
                calamity: $('#calamity').val(),
                calamityImg: $('#calamityImg').val(),
                education: $('#education').val(),
                educationImg: $('#educationImg').val(),
                illness: $('#illness').val(),
                illnessImg: $('#illnessImg').val(),
                reliefAmo: $('#reliefAmo').val(),
                reliefAmoImg: $('#reliefAmoImg').val(),

                //以下帮扶措施
                mifactory: $('#mifactory').val(),
                miffactoryName: $('#miffactoryName').val(),
                mifSalary: $('#mifSalary').val(),
                mifEmpName: $('#mifEmpName').val(),

                planTing: $('#planTing').val(),
                planName: $('#planName').val(),
                planSubsidyAmo: $('#planSubsidyAmo').val(),
                planSales: $('#planSales').val(),
                planNickname: $('#planNickname').val(),

                breed: $('#breed').val(),
                breedName: $('#breedName').val(),
                breedSubsidyAmo: $('#breedSubsidyAmo').val(),
                breedSales: $('#breedSales').val(),
                breedNickname: $('#breedNickname').val(),

                familyWork: $('#familyWork').val(),
                famachinName: $('#famachinName').val(),
                faIncome: $('#faIncome').val(),
                faSales: $('#faSales').val(),
                faNickname: $('#faNickname').val(),

                phoStock: $('#phoStock').val(),
                phoAnnInc: $('#phoAnnInc').val(),
                phoNickName: $('#phoNickName').val(),

                shares: $('#shares').val(),
                equSbName: $('#equSbName').val(),
                equEnter: $('#equEnter').val(),
                equAmo: $('#equAmo').val(),
                equName: $('#equName').val(),

                capAmo: $('#capAmo').val(),
                capEnter: $('#capEnter').val(),
                capBomAmo: $('#capBomAmo').val(),
                capName: $('#capName').val(),

                loan: $('#loan').val(),
                loanMd: $('#loanMd').val(),
                loan_Amo: $('#loan_Amo').val(),
                loanTerm: $('#loanTerm').val(),
                loanPeople: $('#loanPeople').val(),

                poorFamilyImg: $('#poorFamilyImg').val()
            }

            if (isEdit) { //isEdit==1 表示编辑
                var poorViId = mccms.getHash('id') //贫困户id
                data.id = poorViId
                data.addTime = addTime
                if (familyArr.length > 0) {
                    valid &&
                    mccms.ajax({ //新增贫困户API
                        "url": "/poorFa/updatePoorFamily",
                        "cache": false,
                        "method": "POST",
                        "data": data,
                        "dataType": 'json',
                        "contentType": 'application/json',
                        "success": function () {
                            mccms.gobackFromEdit()
                        }
                    })
                } else {
                    layer.msg('请添加家庭成员')
                }


            } else { //isEdit 没有时表示新增
                if (familyArr.length > 0) {
                    valid &&
                    mccms.ajax({ //新增贫困户API
                        "url": "/poorFa/addPoorFamily",
                        "cache": false,
                        "method": "POST",
                        "data": data,
                        "dataType": 'json',
                        "contentType": 'application/json',
                        "success": function () {
                            mccms.goBack()
                        }
                    })
                } else {
                    layer.msg('请添加家庭成员')
                }

            }

        },
        getW = function (params) { //省市县乡村

            //省请求
            _ajaxW(0, function (data) {
                createOption(data, function (cryHtml) {
                    $(".province1").each(function (i, item) {
                        $(item).html(cryHtml)
                    })
                    //省判断选中
                    $('.province1').val(s_province)
                    if (s_province) {
                        $('#province1').attr('disabled', 'disabled')
                    }
                    //市请求
                    _ajaxW(1, function (data) {
                        createOption(data, function (cryHtml) {
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                            //市判断选中
                            $('.city').val(s_city)
                            if (s_city) {
                                $('#city1').attr('disabled', 'disabled')
                            }
                            //县请求
                            _ajaxW(2, function (data) {
                                createOption(data, function (cryHtml) {
                                    $(".county").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                    //县判断选中
                                    $('.county').val(s_cty)
                                    if (s_cty) {
                                        $('#county').attr('disabled', 'disabled')
                                    }
                                    //乡请求
                                    _ajaxW(3, function (data) {
                                        createOption(data, function (cryHtml) {
                                            $('#country').html(cryHtml)
                                            $('#country').val(s_cry)

                                            //村请求
                                            if (s_cry) {
                                                $('#country').attr('disabled', 'disabled')
                                            }
                                            if (params) {
                                                $('#province1').val(params.province)
                                                $('#city1').val(params.city)
                                                $('#county').val(params.county)
                                                $('#country').val(params.country)
                                            }
                                            var countryId = $('#country').find('option:checked').attr('id');
                                            if (params) {
                                                // s_cry_id = countryId
                                            }
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                    $('#village1').val(s_name);
                                                })

                                                if (s_name) {
                                                    $('#village1').attr('disabled', 'disabled')
                                                }
                                                if (params) {
                                                    $("#village1").val(params.village);
                                                }

                                                // //村下拉
                                                // $("#village1").change(function() {
                                                //     village1Id = $(this).find("option:checked").attr("id");
                                                // })
                                                //
                                                // var countryId = $('#country').find('option:checked').attr('id');
                                                // if (params) {
                                                //     /*s_cry_id = countryId*/
                                                // }
                                                // _ajaxW(countryId, function(data) {
                                                //     createOption(data, function(cryHtml) {
                                                //         $("#village1").html(cryHtml);
                                                //     })
                                                //     $('.village1').val(s_name)
                                                //     if (s_name) {
                                                //         $('#village1').attr('disabled', 'disabled')
                                                //     }
                                                //     if (params) {
                                                //         $("#village1").val(params.village);
                                                //     }
                                                //     //村下拉
                                                //     $("#village1").change(function() {
                                                //         village1Id = $(this).find("option:checked").attr("id");
                                                //     });
                                                // })

                                            })
                                        })
                                    })
                                    if (s_cry) {
                                        $('#country').attr('disabled', 'disabled')
                                    } else {
                                        //乡下拉
                                        $("#country").change(function () {
                                            var countryId = $(this).find("option:checked").attr("id");
                                            //村请求
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                            })
                                        });
                                    }
                                })
                            })
                        })
                    })
                })

                //省下拉
                $(".province1").change(function () {
                    var province1Id = $(this).find("option:checked").attr("id");
                    //市请求
                    _ajaxW(province1Id, function (data) {
                        createOption(data, function (cryHtml) {
                            // $("#city").html(cryHtml);
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                        })
                    })
                    //市下拉
                    $(".city").change(function () {
                        var cityId = $(this).find("option:checked").attr("id");
                        //县请求
                        _ajaxW(cityId, function (data) {
                            createOption(data, function (cryHtml) {
                                // $("#county").html(cryHtml);
                                $(".county").each(function (i, item) {
                                    $(item).html(cryHtml)
                                })
                            })
                        })
                        //县下拉
                        $(".county").change(function () {
                            var countyId = $(this).find("option:checked").attr("id");
                            //乡请求
                            _ajaxW(countyId, function (data) {
                                createOption(data, function (cryHtml) {
                                    // $("#country").html(cryHtml);
                                    $(".country").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                })
                            })
                            //乡下拉
                            $("#country").change(function () {
                                var countryId = $(this).find("option:checked").attr("id");


                                //村下拉
                                /*$("#village1").change(function() {
                                    village1Id = $(this).find("option:checked").attr("id");*/


                                //村请求
                                _ajaxW(countryId, function (data) {
                                    createOption(data, function (cryHtml) {
                                        $("#village1").html(cryHtml);
                                    })
                                })

                                //村下拉
                                $("#village1").change(function () {
                                    village1Id = $(this).find("option:checked").attr("id");
                                    getHelpPersonList();
                                });

                            });
                        });
                    });
                });
            })
        },
        _ajaxW = function (id, fn) { //地区请求
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": id
                },
                success: function (data) {
                    return fn(data)
                }
            });
        },
        createOption = function (data, fn) { //创造option
            var cryHtml = '<option value="">请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
            }
            return fn(cryHtml)
        },
        addMethod = function (getClassName, setClassName) { //加法
            var sum = 0;
            $('.' + getClassName).each(function (index, ele) {
                if (ele.value == "") { //导入时为空则赋值为0
                    ele.value = 0
                }
                sum += parseFloat(ele.value);
            })
            $('#' + setClassName).val(sum.toFixed(2))
        }


    // 流程
    //全部保存
    addMain.on('click', '#save-btn', function () {

        myRequired("modelForm", "addPopup"); //必填提示
        subMsg()
    })


    //帮扶日志按钮
    addMain.on('click', "#helpLog-btn", function () { //帮扶
        var poorFamilyId = mccms.getHash('id') //用户ID
        mccms.goTo("povertyStrickenEdit", "visitingRecord", {"poorFamilyId": poorFamilyId,});
    })

    var memberArr = [];

    //页面加载
    //operatedState==1为查看不可编辑,0为可编辑
    if (operatedState == 1) { //查看页面
        getDetail(id)
    }
    if (operatedState == 0) { //编辑页面
        getDetail(id, addTime)
    }
    if (!id) { //新增页面
        getDetail()
    }
}

/*cawiwen 一期重构 1102 end*/


/*嘉欣JavaScript start 0929*/

/*--贫困村出列管理--*/
function poorVillageOutMng() {
    // 变量声明
    var main = $('#MainList'),
        size = 10,
        no = 1,
        pageCount = null,
        size1 = 10,
        no1 = 1,
        pageCount1 = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        urlStr = "&cry=" + s_cry + "&name=" + s_name,
        // id ：操作记录的id
        // operated 0为出列，1为取消出列
        changePop = function (id, operated, chulie) {
            layer.open({
                type: 1,
                area: ['530px', '500px'],
                title: '变更情况',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('.change-box'),
                success: function () {
                    if (!chulie) {
                        $('#chulie-btn').val('出列')
                    } else {
                        $('#chulie-btn').val('取消出列')
                    }
                    //form-change
                    var myDate = new Date();
                    $("#change-date").val(myDate.toLocaleDateString());
                    $("#changes-type").val(operated);
                    $("#reason").val("");
                    $(".input-btn", ".change-box").off().on('click', function () {
                        $("#changes-type").removeAttr("disabled");

                        var index = layer.index;
                        mccms.ajax({
                            //"url": "/naorpo/updatePoor",
                            "url": "/dequCon/addDequeue",
                            "cache": false,
                            "method": "POST",
                            "data": $("#form-change").serialize() + "&pid=" + id,
                            "success": function (data) {
                                layer.close(index);
                                layer.msg('操作成功！');
                                getList(no, size, no1, size1)
                            }
                        })
                    })
                }
            })
        },
        getList = function (pageNo, pageSize, pageNo1, pageSize1, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                mccms.ajax({
                    "url": "/naorpo/queryNaOrPo",
                    "cache": false,
                    "method": "POST",
                    "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&pageNo1=" + pageNo1 + "&pageSize1=" + pageSize1, //pageNo1,pageSize1 为已出列贫困村列表
                    "success": function (data) {
                        //乡选中加载村数据
                        $("#cry").change(function () {
                            cryId = $(this).find("option:checked").attr("id");
                            cryVal = $(this).find("option:checked").val();
                            $("#h-cry").val($(this).find("option:checked").attr("data-number"))
                            $("#h-name").val("") //清空村值
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": cryId
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="" selected>请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#name").html(naturalsHtml);

                                }
                            });
                        });
                        //村选中加载村数据
                        $("#name").change(function () {
                            nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
                            s_name_id = $(this).find("option:checked").attr("data-number");
                            $("#h-name").val(s_name_id);
                        });

                        laydate.render({
                            elem: '#year',
                            type: 'year'
                        });
                        var data1 = {},
                            data2 = {};

                        data1 = data.result.pager; //已出列数据
                        data2 = data.result.pager1; //未出列数据

                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list1",
                            "container": $("#tbody1"),
                            "data": data2,
                            "callback": function () {
                                //出列
                                $('.out_btn').on('click', function () {
                                    //脱贫时改变value与text
                                    $("#changes-type .changesOption").val("0").text("出列原因")
                                    var id = $(this).parent().attr('id');
                                    changePop(id, 0, 0)

                                    //判断是否最后一条数据，是则返回前一页
                                    if (data2.rowCount - (data2.pageSize * (data2.pageNo - 1)) == 1) {
                                        no = data2.pageNo - 1
                                    }
                                })

                                if (!data2.rowCount) {
                                    pageCount = 0;
                                } else {
                                    pageCount = data2.pageCount
                                }
                                var pageCountArr = []
                                if (data2.pageCount <= 1) {
                                    $('#pageBtn').hide()
                                } else {
                                    $('#pageBtn').show()
                                }
                                for (var i = 1; i <= data2.pageCount; i++) {
                                    pageCountArr.push({
                                        pageCount: i
                                    })
                                }
                                data2.pageCount = pageCountArr
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "page",
                                    "container": $("#pageContainer"),
                                    "data": data2,
                                    "callback": function () {
                                        if (!data2.rowCount) { //处理IE兼容性样式问题 ==》 无数据时填充一个空option
                                            $('#pageCount').html('<option></option>')
                                        }

                                        $('#pageSize').val(size)
                                        $('#pageCount').val(no)
                                        $('#pageSize').change(function () {
                                            no = 1
                                            size = this.value
                                            getList(1, size, no1, size1)
                                        })
                                        $('#pageCount').change(function () {
                                            no = Number(this.value)
                                            getList(no, size, no1, size1)
                                        })
                                    }
                                });

                                //点击数据项添加背景色 
                                tdAddBg('tbody1')
                            }
                        });
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list2",
                            "container": $("#tbody2"),
                            "data": data1,
                            "callback": function () {
                                laydate.render({
                                    elem: '#change-date', //指定元素
                                    type: 'date'
                                });
                                //点击数据项添加背景色 
                                tdAddBg('tbody2')

                                // 取消出列
                                $('.unout_btn').on('click', function () {
                                    //脱贫时改变value与text
                                    $("#changes-type .changesOption").val("1").text("取消出列原因")
                                    var id = $(this).parent().attr('id');
                                    changePop(id, 1, 1)
                                    //判断是否最后一条数据，是则返回前一页
                                    if (data1.rowCount - (data1.pageSize * (data1.pageNo - 1)) == 1) {
                                        no1 = data1.pageNo - 1
                                    }
                                })
                                if (!data1.rowCount) {
                                    pageCount1 = 0;
                                } else {
                                    pageCount1 = data1.pageCount
                                }
                                var pageCountArr = []
                                if (data1.pageCount <= 1) {
                                    $('#pageBtn1').hide()
                                } else {
                                    $('#pageBtn1').show()
                                }
                                for (var i = 1; i <= data1.pageCount; i++) {
                                    pageCountArr.push({
                                        pageCount: i
                                    })
                                }
                                data1.pageCount = pageCountArr
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "page1",
                                    "container": $("#pageContainer1"),
                                    "data": data1,
                                    "callback": function () {
                                        if (!data1.rowCount) { //处理IE兼容性样式问题 ==》 无数据时填充一个空option
                                            $('#pageCount1').html('<option></option>')
                                        }

                                        $('#pageSize1').val(size1)
                                        $('#pageCount1').val(no1)
                                        $('#pageSize1').change(function () {
                                            no1 = 1
                                            size1 = this.value
                                            getList(no, size, 1, size1)
                                        })
                                        $('#pageCount1').change(function () {
                                            no1 = this.value
                                            getList(no, size, no1, size1)
                                        })
                                    }
                                });
                            }
                        });
                    }
                })
            });
        };
    // 流程
    ThisYear(); //当前年
    main.on('click', '.queryBtn', function () { //查询
        getList(1, size, 1, size1, 'true');
    });

    //为出列按钮
    $('#firstPage').click(function () {
        if (no === 1) {
            return false
        }
        no = 1
        $('#pageCount').val(no)
        getList(no, size, no1, size1);
    })
    $('#prevPage').click(function () {
        if (no <= 1) {
            return false
        }
        no -= 1
        getList(no, size, no1, size1);
    })
    $('#nextPage').click(function () {
        if (no >= pageCount) {
            return false
        }
        no += 1
        getList(no, size, no1, size1);
    })
    $('#lastPage').click(function () {
        if (no === pageCount) {
            return false
        }
        no = pageCount
        $('#pageCount').val(no)
        getList(no, size, no1, size1);
    })

    //已出列按钮
    $('#firstPage1').click(function () {
        if (no1 === 1) {
            return false
        }
        no1 = 1
        $('#pageCount1').val(no1)
        getList(no, size, no1, size1);
    })
    $('#prevPage1').click(function () {
        if (no1 <= 1) {
            return false
        }
        no1 -= 1
        getList(no, size, no1, size1);
    })
    $('#nextPage1').click(function () {
        if (no1 >= pageCount1) {
            return false
        }
        no1 += 1
        getList(no, size, no1, size1);
    })
    $('#lastPage1').click(function () {
        if (no1 === pageCount1) {
            return false
        }
        no1 = pageCount1
        $('#pageCount1').val(no1)
        getList(no, size, no1, size1);
    })
    getList(no, size, no1, size1);
}


/*嘉欣JavaScript end 0929*/


/*嘉欣JavaScript start 1014*/

/*--县区管理--*/
function countyMng() {
    // 变量声明
    var main = $('#MainList'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看等页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            if (sessionStorage.getItem('backId') == 1) {
                var prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'))
                for (var i in prevFrom) {
                    $('#' + i).val(prevFrom[i])
                }
                backFrom = sessionStorage.getItem('from')
            } else {
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/area/findvaguearea",
                "cache": false,
                "method": "POST",
                "data": backFrom,
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            if (sessionStorage.getItem('backId') == 1) {
                                var pageNo2 = sessionStorage.getItem('pageNo2'),
                                    pageSize2 = sessionStorage.getItem('pageSize2')

                                //分页方法
                                PagingMethods(pageNo2, pageSize2, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });

                }
            })
        };
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("countyMng", "countyMng_msg");
    });
    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("countyMng", "countyMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });
    main.on('click', '.edit_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("countyMng", "countyMng_msg", {"id": id, "fatherId": fatherId, "operated": 0});
    });
    main.on('click', '.del_btn', function () {
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "POST",
            "name": '删除该县区',
            "url": "/area/delectarea",
            "data": {
                id: id
            },
            "sub": true,
            "fn": function () {
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () {
        no = 1
        getList(pageNo, pageSize)
    })
    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val(),
            prevFrom = {
                "area": $('#area').val(),
                "areaCode": $('#areaCode').val(),
                "fatherId": 2
            };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)
}

function countyMsgEdit() {
    // 变量声明
    var id = mccms.getHash('id'), //id
        fatherId = mccms.getHash('fatherId'),
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        form = $('#userForm'),
        path = $('.c-primary'),
        flag = true,
        getDetail = function () {
            mccms.ajax({
                "url": "/area/findareaByIdfathid",
                "cache": false,
                "method": "POST",
                "data": {
                    id: id,
                    fatherId: fatherId
                },
                success: function (data) {
                    data.result[0].detail = operated
                    setForm(data.result[0])
                }
            })
        },
        setForm = function (data) { //填充表单
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "userMsg",
                "container": form,
                "data": data,
                "callback": function () {
                    //验证地方编码唯一性
                    var areaCode = $('#areaCode').val();
                    $('#areaCode').on('blur', function () {
                        var areaCode1 = $('#areaCode').val();
                        if (areaCode1 != areaCode && areaCode1 != "") {
                            mccms.ajax({
                                "url": "/area/verificAreaCode",
                                "data": {
                                    "areaCode": areaCode1
                                },
                                "method": "POST",
                                "lock": true,
                                "success": function (data) {
                                    if (data.status == 400) {
                                        layer.msg('地方编码重复')
                                        flag = false;

                                    } else if (data.status == 200) {
                                        flag = true;
                                    } else {
                                        flag = false;
                                    }
                                }
                            })
                        }

                    })

                    form.mcFormValide(); //绑定表单验证
                    var txt = operated ? '查看县区信息' : '编辑县区信息';
                    id && path.html(txt) //修改模块名称
                }
            })
            form.mcFormValide(); //绑定表单验证
        },
        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/area/updatearea" : "/area/addarea";
            data += '&fatherId=' + 2
            if (!operated) {
                data += '&id=' + id
            }

            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "method": "POST",
                "lock": true,
                "beforeSend": function () {
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": function () {
                    layer.msg('保存成功！')
                    /*
                                            mccms.goBack()*/
                    id ? mccms.gobackFromEdit() : mccms.goBack()
                }
            })
        };
    // 流程
    id ? getDetail() : setForm(),
        form.on('click', '.sub_btn', function () {
            if (flag) {
                subMsg($(this))
            } else {
                layer.msg('地方编码重复')
            }
        })
}

/*--乡镇管理--*/
function countryMng() {
    // 变量声明
    var main = $('#MainList'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/area/findvaguearea",
                "cache": false,
                "method": "POST",
                "data": backFrom,
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");

                        }
                    });
                }
            })
        };
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("countryMng", "countryMng_msg");
    });
    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("countryMng", "countryMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });
    main.on('click', '.edit_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("countryMng", "countryMng_msg", {"id": id, "fatherId": fatherId, "operated": 0});
    });
    main.on('click', '.del_btn', function () {
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "POST",
            "name": '删除该乡镇',
            "url": "/area/delectarea",
            "data": {
                id: id
            },
            "sub": true,
            "fn": function () {
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () {
        getList(pageNo, pageSize)
    });
    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val(),
            "fatherId": $('#fatherId').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)
}

function countryMsgEdit() {

    // 变量声明
    var id = mccms.getHash('id'), //id
        fatherId = mccms.getHash('fatherId'),
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        form = $('#userForm'),
        path = $('.c-primary'),
        flag = true,
        getDetail = function () {
            mccms.ajax({
                "url": "/area/findareaByIdfathid",
                "cache": false,
                "method": "POST",
                "data": {
                    id: id,
                    fatherId: fatherId
                },
                success: function (data) {
                    data.result[0].detail = operated
                    setForm(data.result[0])
                }
            })
        },
        setForm = function (data) { //填充表单
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "userMsg",
                "container": form,
                "data": data,
                "callback": function () {

                    //验证地方编码唯一性
                    var areaCode = $('#areaCode').val();
                    $('#areaCode').on('blur', function () {
                        var areaCode1 = $('#areaCode').val();
                        if (areaCode1 != areaCode && areaCode1 != "") {
                            mccms.ajax({
                                "url": "/area/verificAreaCode",
                                "data": {
                                    "areaCode": areaCode1
                                },
                                "method": "POST",
                                "lock": true,
                                "success": function (data) {
                                    if (data.status == 400) {
                                        layer.msg('地方编码重复')
                                        flag = false;

                                    } else if (data.status == 200) {
                                        flag = true;
                                    } else {
                                        flag = false;
                                    }

                                }
                            })
                        }

                    })


                    form.mcFormValide(); //绑定表单验证
                    var txt = operated ? '查看乡镇信息' : '编辑乡镇信息';
                    id && path.html(txt) //修改模块名称
                }
            })
        },
        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/area/updatearea" : "/area/addarea";
            data += '&fatherId=' + 3
            if (!operated) {
                data += '&id=' + id
            }
            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "method": "POST",
                "lock": true,
                "beforeSend": function () {
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": function () {
                    layer.msg('保存成功！')
                    /*mccms.goBack()*/
                    id ? mccms.gobackFromEdit() : mccms.goBack()
                }
            })

        };
    // 流程
    id ? getDetail() : setForm(),
        form.on('click', '.sub_btn', function () {
            if (flag) {
                subMsg($(this))
            } else {
                layer.msg('地方编码重复')
            }
        })
}

/*--村管理--*/
function villageMng() {
    // 变量声明
    var main = $('#MainList'),
        _id = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getW = function () {
            //乡请求
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": 3
                },
                success: function (data) {
                    var cryHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < data.result.length; i++) {
                        cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                    }
                    $("#country").html(cryHtml);

                    //初始乡
                    $('#country').val(s_cry)
                    if (s_cry) {
                        $('#country').attr('disabled', 'disabled')
                    }
                    _id = $('#country option:checked').attr('id')
                    $('#fatherId').val(_id)
                    getList(pageNo, pageSize)

                    //乡下拉
                    $("#country").change(function () {
                        _id = $(this).find("option:checked").attr("id");
                        $('#fatherId').val(_id)
                        getList(pageNo, pageSize)
                    });
                }
            });
        },
        getList = function (pageNo, pageSize) {
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/area/findvaguearea",
                "cache": false,
                "method": "POST",
                "data": backFrom,
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    if (i == 'fatherId') {
                                        $('#country option').each(function () {
                                            if ($(this).attr('id') == prevFrom[i]) {
                                                $(this).attr('selected', 'selected')
                                            }
                                        })
                                    }
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });
                }
            })
        }
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("villageMng", "villageMng_msg");
    });
    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });
    main.on('click', '.edit_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_msg", {"id": id, "fatherId": fatherId, "operated": 0});
    });
    main.on('click', '.del_btn', function () {
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "POST",
            "name": '删除该村',
            "url": "/area/delectarea",
            "data": {
                id: id
            },
            "sub": true,
            "fn": function () {
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () {
        getList(pageNo, pageSize)
    });
    //bill 新增 街景设置
    main.on('click', '.Street_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        var name = $(this).parents('td').parents('tr').find("td").eq(0).text().split(" ");
        var country = name[0];
        var village = name[1];
        mccms.goTo("villageMng", "villageMng_street", {"id": id, "fatherId": fatherId, "operated": 0, "country": country, "village": village});
    });


    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "fatherId": $('#fatherId').val(),
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getW()
    getList(pageNo, pageSize)
}

/*--bill 贫困村街景设置 start--*/

//获取url参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.hash.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

function villageMsgStreet() {
    // 变量声明
    // 变量声明
    var _id = mccms.getHash('id'),
        flag = true,
        fatherId = mccms.getHash('fatherId'),
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0,//1为查看不可编辑,0为可编辑
        country = GetQueryString("country"),
        village = GetQueryString('village')

    var main = $('#MainList'),
        //_id = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/vision",
                "cache": false,
                "method": "GET",
                "data": {
                    "villageID": _id,
                    "pageNo": pageNo,
                    "pageSize": pageSize
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {

                            $('.del_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                                mccms.operation({
                                    "method": "DELETE",
                                    "name": '删除该街景',
                                    "url": "/vision/" + id,
                                    "data": {
                                        id: id
                                    },
                                    "sub": true,
                                    "fn": function () {
                                        getList(pageNo, pageSize)
                                    }
                                })
                            });

                            $('.edit_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                                var resource = $(this).parents('td').parents('tr').find("td").eq(2).text();
                                mccms.goTo("villageMng", "villageMng_street_msg", {"villageID": _id, "id": id, "resource": resource, "country": country, "village": village});
                            });


                            $("#tbody tr").each(function () {
                                $(this).find("td").eq(0).text($(this).index() + 1)
                            })
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    if (i == 'fatherId') {
                                        $('#country option').each(function () {
                                            if ($(this).attr('id') == prevFrom[i]) {
                                                $(this).attr('selected', 'selected')
                                            }
                                        })
                                    }
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });
                }
            })
        }
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("villageMng", "villageMng_street_msg", {"villageID": _id, "operated": 0, "country": country, "village": village});
    });
    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });

    main.on('click', '.queryBtn', function () {
        getList(pageNo, pageSize)
    });
    //bill 新增 街景设置
    main.on('click', '.Street_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_street", {"id": id, "fatherId": fatherId, "operated": 0});
    });


    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "fatherId": $('#fatherId').val(),
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)
}

/*--bill 贫困村街景设置 end-*/

/*--bill 贫困户街景设置 start--*/

function povertyStrickenMngStreet() {
    // 变量声明
    // 变量声明
    var _id = mccms.getHash('id');
    fatherId = mccms.getHash('fatherId'),
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0,//1为查看不可编辑,0为可编辑
        country = GetQueryString("country"),
        village = GetQueryString('village')

    var main = $('#MainList'),
        //_id = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/poolVision",
                "cache": false,
                "method": "GET",
                "data": {
                    "poolFamilyId": _id,
                    "pageNo": pageNo,
                    "pageSize": pageSize
                },
                "success": function (data) {
                    console.log(data)
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {

                            $('.del_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                                mccms.operation({
                                    "method": "DELETE",
                                    "name": '删除该街景',
                                    "url": "/poolVision/" + id,
                                    "sub": true,
                                    "fn": function () {
                                        getList(pageNo, pageSize)
                                    }
                                })
                            });

                            $('.edit_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                                var resource = $(this).parents('td').parents('tr').find("td").eq(2).text();
                                mccms.goTo("povertyStrickenMng_street", "povertyStrickenMng_street_msg", {"villageID": _id, "id": id, "resource": resource, "country": country, "village": village});
                            });


                            $("#tbody tr").each(function () {
                                $(this).find("td").eq(0).text($(this).index() + 1)
                            })
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    if (i == 'fatherId') {
                                        $('#country option').each(function () {
                                            if ($(this).attr('id') == prevFrom[i]) {
                                                $(this).attr('selected', 'selected')
                                            }
                                        })
                                    }
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });
                }
            })
        }
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("povertyStrickenMng_street", "povertyStrickenMng_street_msg", {"villageID": _id, "operated": 0, "country": country, "village": village});
    });

    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });

    main.on('click', '.queryBtn', function () {
        getList(pageNo, pageSize)
    });
    //bill 新增 街景设置
    main.on('click', '.Street_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_street", {"id": id, "fatherId": fatherId, "operated": 0});
    });


    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "fatherId": $('#fatherId').val(),
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)
}

/*--bill 贫困户街景设置 end--*/


/*--bill 贫困村街景设置新增 start-*/
function villageStreetEdit() {
    // 变量声明
    var _id = mccms.getHash('villageID'),
        flag = true,
        country = decodeURI(GetQueryString("country")),
        village = decodeURI(GetQueryString('village')),
        id = GetQueryString('id'),
        resource = GetQueryString('resource')
    if (id) {
        $(".c-primary").text("编辑街景信息")
        $("#resource").val(resource);
    }
    $("#village").text(village)
    $("#street-btn").on("click", function () {
        url = $("#resource").val();
        if (!url) {
            layer.msg('请输入资源链接！')
        } else {
            mccms.ajax({
                "url": "/vision",
                "data": {
                    "country": country,
                    "village": village,
                    "villageID": _id,
                    "resource": url,
                    "id": id
                },
                "method": id ? "PUT" : "POST",
                "success": function (data) {
                    layer.msg(data.message)
                    history.back(); //返回上一页
                }
            })
        }
    })
}

/*--bill 贫困村街景设置新增 end-*/


/*--bill 贫困户街景设置新增 start-*/
function povertyStrickenMngEdit() {
    // 变量声明
    var _id = mccms.getHash('villageID'),
        flag = true,
        country = decodeURI(GetQueryString("country")),
        village = decodeURI(GetQueryString('village')),
        id = GetQueryString('id'),
        resource = GetQueryString('resource')
    if (id) {
        $(".c-primary").text("编辑街景信息")
        $("#resource").val(resource);
    }
    $("#village").text(village)
    $("#street-btn").on("click", function () {
        url = $("#resource").val();
        if (!url) {
            layer.msg('请输入资源链接！')
        } else {
            mccms.ajax({
                "url": "/poolVision",
                "data": {
                    "country": country,
                    "village": village,
                    "resource": url,
                    "poolFamilyId": _id,
                    "id": id
                },
                "method": id ? "PUT" : "POST",
                "success": function (data) {
                    layer.msg(data.message)
                    history.back(); //返回上一页
                }
            })
        }
    })
}

/*--bill 贫困户街景设置新增 end-*/

function villageMsgEdit() {
    // 变量声明
    var id = mccms.getHash('id'),
        flag = true,
        fatherId = mccms.getHash('fatherId'),
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        form = $('#userForm'),
        path = $('.c-primary'),
        getDetail = function () {
            mccms.ajax({
                "url": "/area/findareaByIdfathid",
                "cache": false,
                "method": "POST",
                "data": {
                    id: id,
                    fatherId: fatherId
                },
                success: function (data) {
                    data.result[0].detail = operated
                    setForm(data.result[0])
                }
            })
        },
        setForm = function (data) { //填充表单
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "userMsg",
                "container": form,
                "data": data,
                "callback": function () {
                    //验证地方编码唯一性
                    var areaCode = $('#areaCode').val();
                    $('#areaCode').on('blur', function () {
                        var areaCode1 = $('#areaCode').val();
                        if (areaCode1 != areaCode && areaCode1 != "") {
                            mccms.ajax({
                                "url": "/area/verificAreaCode",
                                "data": {
                                    "areaCode": areaCode1
                                },
                                "method": "POST",
                                "lock": true,
                                "success": function (data) {
                                    if (data.status == 400) {
                                        layer.msg('地方编码重复')
                                        flag = false;

                                    } else if (data.status == 200) {
                                        flag = true;
                                    } else {
                                        flag = false;
                                    }
                                }
                            })
                        }

                    })
                    form.mcFormValide(); //绑定表单验证
                    getW()
                    var txt = operated ? '查看村信息' : '编辑村信息';
                    id && path.html(txt) //修改模块名称


                }
            })
        },
        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/area/updatearea" : "/area/addarea";
            data += '&fatherId=' + fatherId
            if (!operated) {
                data += '&id=' + id
            }
            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "method": "POST",
                "lock": true,
                "beforeSend": function () {
                    ele && ele.attr('disabled', 'disabled');
                },
                "complete": function () {
                    ele && ele.removeAttr('disabled');
                },
                "success": function () {
                    layer.msg('保存成功！')
                    id ? mccms.gobackFromEdit() : mccms.goBack() //  编辑/查看:新增
                }
            })
        },
        getW = function () {
            //乡请求
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": 3
                },
                success: function (data) {
                    var cryHtml = '<option value="" class="please">请选择</option>';
                    for (var i = 0; i < data.result.length; i++) {
                        cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                    }
                    $("#country").html(cryHtml);
                    //乡下拉
                    $("#country").change(function () {
                        fatherId = $(this).find("option:checked").attr("id");
                    })
                    //乡权限控制
                    if ($("input[name='cry']").attr("data-id") || $("input[name='name']").attr("data-id")) {
                        var cryAreaId = $("input[name='cry']").attr("data-id"); //乡的area id
                        $("#country option").each(function () {
                            if (cryAreaId == $(this).attr("data-number")) {
                                $(".please").remove();
                                $(this).attr("selected", "selected"); //选定状态
                                $("#country").attr("disabled", "disabled"); //禁用状态
                                fatherId = $(this).attr("id"); //id值
                            }
                        })

                    }

                    $('#country option').each(function (i, item) {
                        if ($(item).attr('id') === fatherId) {
                            $(item).attr('selected', 'selected')
                            //村请求
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": fatherId
                                },
                                success: function (data) {
                                    var cryHtml = '<option value="">请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#village").html(cryHtml)
                                }
                            })
                            return
                        }
                    })
                }
            });
        };
    // 流程
    id ? getDetail() : setForm();
    form.on('click', '.sub_btn', function () {
        if (flag) {
            subMsg($(this))
        } else {
            layer.msg('地方编码重复')
        }

    })
}

// jiaxin end

/*-- 负责人维护帮扶单位 start--*/
function guardianMng() {
    // 变量声明
    var main = $('#MainList'),
        form = $('#searchForm'), //查询表单
        valid = form.valid(), //表单验证
        operated = 0,
        size = 10,
        no = 1,
        pageCount = null,
        size1 = 10,
        no1 = 1,
        pageCount1 = null,
        HELP_UNIT, //存储帮扶单位id
        countryCode = $("input[name=cry]").attr("data-id"); //乡的areaCode编码;用做权限控制
    if (!countryCode) {
        countryCode = ""
    } //当用户为县以及以上级别时,不做权限控制
    var getList = function (pageNo, pageSize, nowId) {
            //nowId为选定状态的帮扶责任人的id
            if (!pageNo) {
                pageNo = 1
            }
            //帮扶负责人数据请求和列表展示
            mccms.ajax({
                "url": "/helppeson/findAllhelppeson",
                "cache": false,
                "method": "POST",
                "data": "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&" + $("#searchForm").serialize(),
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list1",
                        "container": $("#tbody1"),
                        "data": data.result,
                        "callback": function () {
                            //改变td line-height
                            $("#tbody1 tr td").css("line-height", "27px")

                            /*加选定状态 start*/
                            // $("#tbody1 input[name=radio]").each(function() {
                            //     var dataId = $(this).attr("data-id");
                            //     if (dataId == nowId) {
                            //         $("#tbody1 input[data-id=" + nowId + "]").attr("checked", "true");
                            //     }
                            // })
                            /*加选定状态 end*/

                            /*有选定状态时刷新-帮扶单位 start*/
                            $('#tbody1 input[name=radio]').on("click", function () {
                                var helpUnitId = $(this).attr("data-id") //帮扶负责人id
                                getList1(helpUnitId)
                            })
                            /*有选定状态时刷新-帮扶单位 end*/


                            if (!data.result.rowCount) {
                                pageCount = 0;
                            } else {
                                pageCount1 = data.result.pageCount
                            }
                            var pageCountArr = []
                            if (data.result.pageCount <= 1) {
                                $('#pageBtn1').hide()
                            } else {
                                $('#pageBtn1').show()
                            }
                            for (var i = 1; i <= data.result.pageCount; i++) {
                                pageCountArr.push({
                                    pageCount: i
                                })
                            }
                            data.result.pageCount = pageCountArr
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "page1",
                                "container": $("#pageContainer1"),
                                "data": data.result,
                                "callback": function () {
                                    $('#pageSize1').val(size1)
                                    $('#pageCount1').val(no1)
                                    $('#pageSize1').change(function () {
                                        no1 = 1
                                        size1 = this.value
                                        getList(1, size1)
                                    })
                                    $('#pageCount1').change(function () {
                                        no1 = this.value
                                        getList(no1, size1)
                                    })


                                }
                            })


                        }
                    });
                }
            })
        },
        //帮扶单位
        getList1 = function (id) {
            mccms.ajax({
                "url": "/helppeson/findhelpunits",
                "cache": false,
                "method": "POST",
                "data": {
                    id: id
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list2",
                        "container": $("#tbody2"),
                        "data": data,
                        "callback": function () {
                            //改变td line-height
                            $("#tbody2 tr td").css("line-height", "27px")
                        }
                    });
                    HELP_UNIT = data.result[0].id; //选择帮扶人责任人对应的帮扶单位id
                    mccms.pageHtml(data, getList, [], "layerPage2")
                }
            })
        },
        //弹窗-单位信息
        getHelpList = function (pageNo, pageSize, id, HELP_UNIT) {
            //显示所有单位
            mccms.ajax({
                "url": "/helpu/findAllhelpunits",
                "cache": false,
                "method": "POST",
                "data": $("#unitSearchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list4",
                        "container": $("#tbody3"),
                        "data": data.result,
                        "callback": function () {
                            //选中弹窗的所属单位
                            $("#all-unit").find("input[value=" + HELP_UNIT + "]").prop("checked", true);

                            //编辑保存
                            $(".save-btn", '#add').off().on('click', function () {
                                var id = $("#tbody1 input[name='radio']:checked").attr("data-id"); //帮扶负责人id
                                var unit_name = $("#tbody3 input[name='HELP_UNIT']:checked").attr("data-unitname"); //帮扶单位名称
                                mccms.ajax({
                                    "url": "/helppeson/updatehelpperson",
                                    "cache": false,
                                    "method": "POST",
                                    "data": $("#all-unit").serialize() + "&id=" + id + "&unit_name=" + unit_name,
                                    "success": function (data) {
                                        var nowId = $('#tbody1 input[name=radio]:checked').attr("data-id"); //选定状态帮扶责任人id

                                        layer.closeAll(); //关闭弹窗
                                        no1 = 1
                                        getList(1, size1, nowId); //刷新帮扶责任人
                                    }
                                })

                            })

                            //分页
                            if (!data.result.rowCount) {
                                pageCount = 0;
                            } else {
                                pageCount = data.result.pageCount
                            }
                            var pageCountArr = []
                            if (data.result.pageCount <= 1) {
                                $('#pageBtn').hide()
                            } else {
                                $('#pageBtn').show()
                            }
                            for (var i = 1; i <= data.result.pageCount; i++) {
                                pageCountArr.push({
                                    pageCount: i
                                })
                            }
                            data.result.pageCount = pageCountArr
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "page",
                                "container": $("#pageContainer"),
                                "data": data.result,
                                "callback": function () {

                                    $('#pageSize').val(data.result.pageSize)
                                    $('#pageCount').val(data.result.pageNo)
                                    $('#pageSize').change(function () {
                                        no = 1
                                        size = this.value
                                        getHelpList(1, size)
                                    })
                                    $('#pageCount').change(function () {
                                        no = Number(this.value)
                                        getHelpList(no, size)
                                    })
                                }
                            });
                        }
                    })
                }
            })
        },
        // id ：修改的帮扶负责人id
        // HELP_UNIT ： 根据选中的帮扶负责人HELP_UNIT去选中弹窗中的所属单位
        subForm = function (id, HELP_UNIT) {
            layer.open({
                type: 1,
                area: ['80%', '80%'],
                title: '修改',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('#add'),
                success: function () {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list3",
                        "container": $("#add"),
                        "data": {},
                        "callback": function () {
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": 3
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="" selected>请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#cry").html(naturalsHtml);
                                    if (s_cry) {
                                        $("#cry").val(s_cry)
                                        $("#cry").attr('disabled', 'disabled')
                                    }
                                    $("#cry").change(function () {
                                        var cryCode = $("#cry option:checked").attr("data-number");
                                        $("#h-cry").val(cryCode)
                                    })

                                }
                            });

                            $('.queryBtn').on('click', function () {
                                getHelpList(no, size, id, HELP_UNIT)
                            })

                            getHelpList(1, 10, id, HELP_UNIT)

                            //分页
                            $('#firstPage').click(function () {
                                if (no === 1) {
                                    return false
                                }
                                no = 1
                                $('#pageCount').val(no)
                                getHelpList(no, size)
                            })
                            $('#prevPage').click(function () {
                                if (no <= 1) {
                                    return false
                                }
                                no -= 1
                                getHelpList(no, size)
                            })
                            $('#nextPage').click(function () {
                                if (no >= pageCount) {
                                    return false
                                }
                                no += 1
                                getHelpList(no, size)
                            })
                            $('#lastPage').click(function () {
                                if (no === pageCount) {
                                    return false
                                }
                                no = pageCount
                                $('#pageCount').val(no)
                                getHelpList(no, size)
                            })
                        }
                    });

                }
            });

        }
    // 流程
    main.on('click', '.query-btn', function () { //帮扶单位查询
        getList(no1, size1); //查询后刷新页面
    });

    //点击 修改弹窗
    $('#edit').on('click', function () {
        var id = $('#tbody1 input[name=radio]:checked').attr("data-id"); //选定状态帮扶负责人id
        id ? subForm(id, HELP_UNIT) : layer.msg("请先选择帮扶负责人");
    })

    $('#firstPage1').click(function () {
        if (no1 === 1) {
            return false
        }
        no1 = 1
        $('#pageCount1').val(no1)
        getList(no1, size1)
    })
    $('#prevPage1').click(function () {
        if (no1 <= 1) {
            return false
        }
        no1 -= 1
        getList(no1, size1)
    })
    $('#nextPage1').click(function () {
        if (no1 >= pageCount1) {
            return false
        }
        no1++
        getList(no1, size1)
    })
    $('#lastPage1').click(function () {
        if (no1 === pageCount1) {
            return false
        }
        no1 = pageCount1
        $('#pageCount1').val(no1)
        getList(no1, size1)
    })
    getList(no1, size1);
}

/*-- 负责人维护帮扶单位 end--*/

//首页 start
/*function welcome2() {
    var arr1 = [],
        arr2 = [];
    //获取统计图容器大小
    var dWidth = $("#container").width() * 45 / 100,
        dHeight = $("#container").width() * 30 / 100,
        dWidth2 = $("#container").width() * 91.5 / 100;
    //设置统计图容器宽度
    $('.nav_header').width(dWidth2)
    $(".wp-50").width(dWidth);
    $(".chart-div").height(dHeight);
    $(".wp-100").width(dWidth2);

    $(window).resize(function() { //窗口变化，重新绘图
        //获取统计图容器大小
        var dWidth = $("#container").width() * 45 / 100,
            dHeight = $("#container").width() * 30 / 100,
            dWidth2 = $("#container").width() * 91.5 / 100;
        //设置统计图容器宽度
        $('.nav_header').width(dWidth2)
        $(".wp-50").width(dWidth);
        $(".chart-div").height(dHeight);
        $(".wp-100").width(dWidth2);
    });

    //柱状图--贫困村信息
    mccms.ajax({
        "url": "/poorVi/NemberPoorVillages",
        "cache": false,
        "method": "GET",
        "success": function(data) {
            var result = data.result,
                arr1 = [],
                arr2 = [];
            for (var i = 0; i < result.length; i++) {

                arr1.push(result[i].name) //获取x轴
                arr2.push(result[i].value) //获取y轴
            }
            var ymax = Math.max.apply(null, arr2) + 0.5; //y轴的高度0~ymax,
            //填充图表

            statisticsChart("totalFamily", arr1, arr2, ymax)
            $(window).resize(function() {
                statisticsChart("totalFamily", arr1, arr2, ymax)
            });
            $('.icon-arrow').on('click', function() {
                setTimeout(function() {
                    var dWidth = $("#container").width() * 45 / 100,
                        dHeight = $("#container").width() * 30 / 100,
                        dWidth2 = $("#container").width() * 91.5 / 100;
                    //设置统计图容器宽度
                    $('.nav_header').width(dWidth2)
                    $(".wp-50").width(dWidth);
                    $(".chart-div").height(dHeight);
                    $(".wp-100").width(dWidth2);
                    statisticsChart("totalFamily", arr1, arr2, ymax)
                }, 100)


            })
        }
    });

    //饼图--贫困户信息
    mccms.ajax({
        "url": "/poorFa/totalFamily",
        "cache": false,
        "method": "GET",
        "success": function(data) {
            var result = data.result,
                arr1 = [],
                arr2 = [];
            for (var i = 0; i < result.length; i++) {
                arr1.push(result[i].name) //获取x轴
                arr2.push(result[i].value) //获取y轴
            }
            //填充图表
            pieList("povertyStrickenMes", arr1, arr2, result);
            $(window).resize(function() {
                pieList("povertyStrickenMes", arr1, arr2, result);
            });
            $('.icon-arrow').on('click', function() {
                setTimeout(function() {
                    var dWidth = $("#container").width() * 45 / 100,
                        dHeight = $("#container").width() * 30 / 100,
                        dWidth2 = $("#container").width() * 91.5 / 100;
                    //设置统计图容器宽度
                    $('.nav_header').width(dWidth2)
                    $(".wp-50").width(dWidth);
                    $(".chart-div").height(dHeight);
                    $(".wp-100").width(dWidth2);
                    pieList("povertyStrickenMes", arr1, arr2, result);
                }, 100)


            })
        }
    });

    //柱状图--帮扶单位信息
    mccms.ajax({
        "url": "/poorFa/unitsNumber",
        "cache": false,
        "method": "GET",
        "success": function(data) {
            var result = data.result,
                arr1 = [],
                arr2 = [];
            for (var i = 0; i < result.length; i++) {
                arr1.push(result[i].name) //获取x轴
                arr2.push(result[i].value) //获取y轴
            }
            var ymax = Math.max.apply(null, arr2) + 0.5; //y轴的高度0~ymax,
            //填充图表
            statisticsChart("helpUnitMng", arr1, arr2, ymax)
            $(window).resize(function() {
                statisticsChart("helpUnitMng", arr1, arr2, ymax)
            });
            $('.icon-arrow').on('click', function() {
                setTimeout(function() {
                    var dWidth = $("#container").width() * 45 / 100,
                        dHeight = $("#container").width() * 30 / 100,
                        dWidth2 = $("#container").width() * 91.5 / 100;
                    //设置统计图容器宽度
                    $('.nav_header').width(dWidth2)
                    $(".wp-50").width(dWidth);
                    $(".chart-div").height(dHeight);
                    $(".wp-100").width(dWidth2);
                    statisticsChart("helpUnitMng", arr1, arr2, ymax)
                }, 100)
            })
        }
    });

    //南丁格尔玫瑰图--致贫原因
    mccms.ajax({
        "url": "/poorFa/poorCauseStat",
        "cache": false,
        "method": "GET",
        "success": function(data) {
            var result = data.result,
                arr1 = [],
                arr2 = [];
            for (var i = 0; i < result.length; i++) {
                arr1.push(result[i].name) //获取x轴
                arr2.push(result[i].value) //获取y轴
            }
            //填充图表
            poorReason("poorReason", arr1, arr2, result)
            $(window).resize(function() {
                poorReason("poorReason", arr1, arr2, result)
            });
            $('.icon-arrow').on('click', function() {
                setTimeout(function() {
                    var dWidth = $("#container").width() * 45 / 100,
                        dHeight = $("#container").width() * 30 / 100,
                        dWidth2 = $("#container").width() * 91.5 / 100;
                    //设置统计图容器宽度
                    $('.nav_header').width(dWidth2)
                    $(".wp-50").width(dWidth);
                    $(".chart-div").height(dHeight);
                    $(".wp-100").width(dWidth2);
                    poorReason("poorReason", arr1, arr2, result)
                }, 100)

            })
        }
    });

    /*incomeMes("incomeMes")*/
//折线图---收入信息
/*mccms.ajax({
        "url": "/area/income",
        "cache": false,
        "method": "GET",
        "success": function(data) {
            var result = data.result,
                arr1 = [],
                arr2 = [];
            for (var i = 0; i < result.length; i++) {
                arr1.push(result[i].name) //获取x轴
                arr2.push(result[i].value) //获取y轴
            }
            //填充图表
            incomeMes("incomeMes", arr1, arr2, result)
            $(window).resize(function() {
                incomeMes("incomeMes", arr1, arr2, result)
            });
            $('.icon-arrow').on('click', function() {
                setTimeout(function() {
                    var dWidth = $("#container").width() * 45 / 100,
                        dHeight = $("#container").width() * 30 / 100,
                        dWidth2 = $("#container").width() * 91.5 / 100;
                    //设置统计图容器宽度
                    $('.nav_header').width(dWidth2)
                    $(".wp-50").width(dWidth);
                    $(".chart-div").height(dHeight);
                    $(".wp-100").width(dWidth2);
                    incomeMes("incomeMes", arr1, arr2, result)
                }, 100)


            })
        }
    });

}*/

function welcome() {
    var arr1 = [],
        arr2 = [],
        dWidth,
        dHeight,
        dWidth2,
        DataArr = [{
            //贫困村信息
            "url": '/poorVi/NemberPoorVillages',
            'id': 'totalFamily',
        }, {
            //贫困村信息
            "url": '/poorFa/totalFamily',
            'id': 'povertyStrickenMes',
        }, {
            //帮扶单位信息
            'url': '/poorFa/unitsNumber',
            'id': 'helpUnitMng'
        }, {
            //致贫原因
            'url': '/poorFa/poorCauseStat',
            'id': 'poorReason'
        }, {
            //收入信息
            'url': '/area/income',
            'id': 'incomeMes'
        }],
        getContain = function (callback) { //根据父级宽度设置图表容器宽高
            dWidth = $("#container").width() * 45 / 100,
                dHeight = $("#container").width() * 30 / 100,
                dWidth2 = $("#container").width() * 91.5 / 100;
            //设置统计图容器宽度
            $('.nav_header').width(dWidth2)
            $(".wp-50").width(dWidth);
            $(".chart-div").height(dHeight);
            $(".wp-100").width(dWidth2);
            if (callback) {
                callback()
            }
        },
        fnList = function (index, id, arr1, arr2, ymax, result) { //绘制图表
            getContain()
            if (index == 0 || index == 2) { // 0为贫困村信息  2为帮扶单位信息
                statisticsChart(id, arr1, arr2, ymax)
                $(window).resize(function () { //窗口变化，重新绘图
                    getContain()
                    statisticsChart(id, arr1, arr2, ymax)
                });
            }
            if (index == 1) {
                pieList(id, arr1, arr2, result)
                $(window).resize(function () { //窗口变化，重新绘图
                    getContain()
                    pieList(id, arr1, arr2, result)
                });
            }
            if (index == 3) {
                poorReason(id, arr1, arr2, result)
                $(window).resize(function () { //窗口变化，重新绘图
                    getContain()
                    poorReason(id, arr1, arr2, result)
                });
            }
            if (index == 4) {
                incomeMes(id, arr1, arr2, result)
                $(window).resize(function () { //窗口变化，重新绘图
                    getContain()
                    incomeMes(id, arr1, arr2, result)
                });
            }

        },
        getList = function (arr) {
            getContain();
            arr.forEach(function (v, index) {
                mccms.ajax({ //请求图表数据
                    "url": v.url,
                    "cache": false,
                    "method": "GET",
                    "success": function (data) {
                        var result = data.result,
                            arr1 = [],
                            arr2 = [];
                        for (var i = 0; i < result.length; i++) {

                            arr1.push(result[i].name) //获取x轴
                            arr2.push(result[i].value) //获取y轴
                        }
                        var ymax = Math.max.apply(null, arr2) + 0; //y轴的高度0~ymax,
                        //填充图表
                        fnList(index, v.id, arr1, arr2, ymax, result)
                        $('.icon-arrow').on('click', function () {
                            setTimeout(function () {
                                fnList(index, v.id, arr1, arr2, ymax, result)
                            }, 100)


                        })
                    }
                });
            })
        };

    getList(DataArr);
}

//首页 end

//统计图---柱状图
/*
    idName:容器id
    xArr：x坐标数组
    yArr:y坐标数组
*/
function statisticsChart(idName, xArr, yArr, ymax) {
    // 基于准备好的dom，初始化echarts图表
    var myChart = echarts.init(document.getElementById(idName));
    var option = {
        tooltip: {
            show: true
        },
        legend: {
            data: ['乡镇']
        },
        xAxis: [{
            type: 'category',
            splitLine: {show: false}, //去除网格线
            axisLabel: {
                interval: 0,
                formatter: function (value) {
                    return value.split("").join("\n");
                }
            },
            data: xArr
        }],
        yAxis: [{
            type: 'value',
            splitArea: {show: true}, //保留网格区域
            max: ymax,
        }],
        series: [{
            "name": "乡镇",
            "type": "bar",
            "data": yArr,
            "itemStyle": {
                normal: {
                    color: '#92C5AB'
                }
            },

        }],
        grid: {
            x: 25,
            y: 20,
            x2: 25,
            y2: 90,

            borderWidth: 1
        }
    };

    // 为echarts对象加载数据 
    myChart.setOption(option);
    //根据窗口大小自适应图表
    /*resizeContain(statisticsChart(idName, xArr, yArr, ymax))*/
}

//首页  end

//饼图 ---贫困户信息
/*
    idName:容器id
    xArr：x坐标数组
    yArr:y坐标数组
    result:后台数据（包含x轴和y轴）
*/
function pieList(idName, xArr, yArr, result) {
    var json = result;
    // 基于准备好的dom，初始化echarts图表
    var myChart = echarts.init(document.getElementById(idName));
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            data: []
        },
        color: ['#C33531', '#EFE42A', '#64BD3D', '#EE9201', '#29AAE3',
            '#B74AE5', '#0AAF9F', '#E89589'
        ],
        toolbox: {
            show: false,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%',
                            width: '30%',
                            funnelAlign: 'left',
                            max: 1548
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        calculable: false,
        series: [{
            name: '访问来源',
            type: 'pie',
            radius: '70%',
            center: ['50%', '50%'],
            data: result
        }]
    };
    // 为echarts对象加载数据 
    myChart.setOption(option);
    /*resizeContain(pieList(idName, xArr, yArr, result))*/
}

//南丁格尔玫瑰图
/*
     idName:容器id
    xArr：x坐标数组
    yArr:y坐标数组
    result:后台数据（包含x轴和y轴）
*/
function poorReason(idName, xArr, yArr, result) {
    var myChart = echarts.init(document.getElementById(idName));
    var json = result;
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            x: 'center',
            y: 'bottom',
            data: []
        },
        toolbox: {
            show: false,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            width: '20%',
                            funnelAlign: 'left',
                            max: 10
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        color: ['#C33531', '#EFE42A', '#64BD3D', '#EE9201', '#29AAE3',
            '#B74AE5', '#0AAF9F', '#E89589'
        ],
        calculable: true,
        series: [{
            name: '致贫原因',
            type: 'pie',
            radius: '80%',
            center: ['50%', "50%"],
            roseType: 'area',
            x: '20%', // for funnel
            max: 20, // for funnel
            sort: 'ascending', // for funnel
            data: json
        }]
    };
    // 为echarts对象加载数据 
    myChart.setOption(option);
    /*resizeContain(poorReason(idName, xArr, yArr, result))*/
}

//折线图
/*
     idName:容器id
    xArr：x坐标数组
    yArr:y坐标数组
    result:后台数据（包含x轴和y轴）
*/
function incomeMes(idName, xArr, yArr, result) {

    var myChart = echarts.init(document.getElementById(idName));
    var json = result;
    var option = {

        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: []
        },

        toolbox: {
            show: false,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        calculable: true,
        xAxis: [{
            type: 'category',
            boundaryGap: false,
            data: xArr,
            splitArea: {show: true}, //保留网格区域
            axisLabel: {
                interval: 0,
                formatter: function (value) {
                    return value.split("").join("\n");
                }
            }
        }],
        yAxis: [{
            type: 'value',
            splitArea: {show: false}, //保留网格区域

        }],
        series: [{
            name: '平均收入',
            type: 'line',
            smooth: true,
            itemStyle: {normal: {areaStyle: {type: 'default'}}},
            data: yArr
        }],
        grid: {
            y: 10,
            y2: 90,
            borderWidth: 1
        }
    };

    // 为echarts对象加载数据 
    myChart.setOption(option);
    /*resizeContain(incomeMes(idName, xArr, yArr, result))*/
}

//证件号码重复查询
function IdNumberInquire() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            areaSelected(cryVal, nameVal, checkType, function () { //areaSelected() 权限控制方法
                console.log("backId:" + sessionStorage.getItem('backId'))

                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({ //贫困户学生查询API
                    "url": "/poorFa/queryDuplicateID",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "mainList",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == 'cry') {
                                            /* $('#' + i).find('option:selected').text(prevFrom[i])*/
                                            $('#cry option').each(function (index, el) { //回显乡名
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-cry").val($(this).attr("data-number")) //乡code值回显
                                                    cryVal = prevFrom[i] //不赋值点击上下页查询条件被清空
                                                }
                                            });
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");

                                //点击数据项添加背景色
                                tdAddBg('tbody')
                                cryAndNameChange();
                                $('#cry').change(function (event) {
                                    /* Act on the event */
                                    cryVal = $(this).find('option:selected').val() //获取乡选择，用于查询条件回显，若不获取，条件会被重置
                                });
                            }
                        });
                    }
                })
            });
        };

    //初始化年度时间
    laydate.render({
        elem: '#year', //指定元素
        type: 'year'
    })
    // 流程
    ThisYear(); //当前年
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')
    });
    main.on('click', '.detail_btn', function () { //查看
        var pid = $(this).parent().attr("pid");
        mccms.goTo("IdNumberInquire", "povertyStrickenEdit", {
            "id": pid,
            "operatedState": 1,
            "inquire": 1,
            "detail": 1
        }); //跳转至《扶贫对象管理》的《贫困户管理》的查看页。inquire: 1,表示查询账表
    });
    main.on('click', ".export_btn", function () {
        location.href = "poorFa/exportDuplicateID?" + $("#searchForm").serialize();
    });
    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "year": $('#year').val(),
            "cry": $('#cry').val(),
            'h-cry': $('#h-cry').val()

        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    //初始化数据
    getList(pageNo, pageSize);
}

//贫困户学生查询
function poorStudentInquire() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            areaSelected(cryVal, nameVal, checkType, function () { //areaSelected() 权限控制方法
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({ //贫困户学生查询API
                    "url": "/poorFa/poorStudent",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "mainList",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == "cry") {
                                            $('#cry option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-cry").val($(this).attr("data-number")) //乡code值回显
                                                }
                                            })
                                            cryVal = prevFrom[i] //乡赋值，用于分页点击之后回显
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            $('#name option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-name").val($(this).attr("data-number")) //村code值回显
                                                }
                                            })
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");

                                //点击数据项添加背景色
                                tdAddBg('tbody')
                                cryAndNameChange();
                                //乡回显
                                $('#cry').change(function (event) {
                                    /* Act on the event */
                                    cryVal = $(this).find('option:selected').val() //获取乡选择，用于查询条件回显，若不获取，条件会被重置
                                })
                                //村回显
                                $('#name').change(function (event) {
                                    /* Act on the event */
                                    nameVal = $(this).find('option:selected').val() //获取村选择，用于查询条件回显，若不获取，条件会被重置
                                })

                            }
                        });
                    }
                })
            });
        };
    ThisYear(); //当前年
    //初始化年度时间
    laydate.render({
        elem: '#year', //指定元素
        type: 'year'
    })
    laydate.render({
        elem: '#enterTime', //指定元素
        type: 'date'
    })
    //学制下拉选择
    selectChange('institution');
    //是否在校生选择
    selectChange('isStudent');
    // 流程
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')
    });
    main.on('click', '.detail_btn', function () { //查看
        var pid = $(this).parent().attr("pid");
        mccms.goTo("poorStudentInquire", "povertyStrickenEdit", {
            "id": pid,
            "operatedState": 1,
            "inquire": 1,
            "detail": 1
        }); //跳转至《扶贫对象管理》的《贫困户管理》的查看页。inquire: 1,表示查询账表
    });
    main.on('click', ".export_btn", function () {
        location.href = "poorFa/exportPoorStudent?" + $("#searchForm").serialize();
    });
    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "year": $('#year').val(),
            "cry": $('#cry').val(),
            "name": $('#name').val(),
            "stuName": $('#stuName').val(),
            "idNumber": $('#idNumber').val(),
            "schoolName": $('#schoolName').val(),
            "enterTime": $('#enterTime').val(),
            "institution": $('#institution').val(),
            "isStudent": $('#isStudent').val(),
            "institution": $('#institution').val(),
            "h-cry": $('#h-cry').val(),
            "h-name": $('#h-name').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    //初始化数据
    getList(pageNo, pageSize);
}

//贫困户户主异常查询
function povertyStrickenUlInquire() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            areaSelected(cryVal, nameVal, checkType, function () { //areaSelected() 权限控制方法
                console.log("backId--:" + sessionStorage.getItem('backId'))
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({ //贫困户学生查询API
                    "url": "/poorFa/exceptH",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "mainList",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    /*for (var i in prevFrom) {
                                        if (i == "cry") {
                                            cryVal = prevFrom[i]
                                            $('#cry option').each(function(index, el) {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                }
                                            });
                                            $('#cry').trigger('change')
                                        } else if (i == 'name') {
                                            $('#' + i).find('option:selected').text(prevFrom[i])
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }*/
                                    for (var i in prevFrom) {
                                        if (i == "cry") {
                                            cryVal = prevFrom[i]
                                            $('#cry option').each(function (index, el) {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-cry").val($(this).attr("data-number")) //乡code值回显
                                                }
                                            });
                                        } else if (i == 'name') {
                                            $('#name option').each(function (index, el) {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    $("#h-name").val($(this).attr("data-number")) //村code值回显
                                                }
                                            });
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");
                                //点击数据项添加背景色
                                tdAddBg('tbody')
                                cryAndNameChange();
                                //乡回显
                                $('#cry').change(function (event) {
                                    /* Act on the event */
                                    cryVal = $(this).find('option:selected').val() //获取乡选择，用于查询条件回显，若不获取，条件会被重置
                                })
                                //村回显
                                $('#name').change(function (event) {
                                    /* Act on the event */
                                    nameVal = $(this).find('option:selected').val() //获取村选择，用于查询条件回显，若不获取，条件会被重置
                                })
                            }
                        });
                    }
                })
            });
        };
    ThisYear(); //当前年

    laydate.render({
        elem: '#year', //指定元素
        type: 'year',
    })
    //获取异常类型
    $('#type').change(function () {
        var type = $(this).find("option:checked").val();
        $("#h_type").val(type)
    })
    //初始化数据
    getList(pageNo, pageSize)

    // 流程
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')
    });
    main.on('click', '.detail_btn', function () { //查看
        var pid = $(this).parent().attr("pid");
        mccms.goTo("povertyStrickenUlInquire", "povertyStrickenEdit", {
            "id": pid,
            "operatedState": 1,
            "inquire": 1,
            "detail": 1
        }); //跳转至《扶贫对象管理》的《贫困户管理》的查看页。inquire: 1,表示查询账表
    });
    main.on('click', ".export_btn", function () {
        location.href = "poorFa/exportExceptH?" + $("#searchForm").serialize()
    });
    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "year": $('#year').val(),
            "cry": $('#cry option:selected').text(),
            "name": $('#name option:selected').text(),
            "type": $('#type').val(),
            "h-cry": $('#h-cry').val(),
            "h-name": $('#h-name').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
}

//下拉菜单改变
function selectChange(idName) {
    $("#" + idName).change(function (event) {
        /* Act on the event */
        var selectChange = $(this).find("option:checked").val();
        $("#h_" + idName).val(selectChange)
    });
}

function visitingRecord() {
    var poorFamilyId = mccms.getHash('poorFamilyId'),
        main = $('#memberManage'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            mccms.ajax({
                "url": "/visitRecd/getVisitRecdPager",
                "cache": false,
                "method": "POST",
                "data": $("#searchForm").serialize() + "&poorFamily.id=" + poorFamilyId + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                "success": function (data) {
                    var data = data;

                    mccms.getHbs({
                        "local": true,
                        "hbsName": "mainList",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            //分页方法
                            PagingMethods(pageNo, pageSize, data, getList);

                            //点击数据项添加背景色
                            tdAddBg('tbody')
                            cryAndNameChange()
                            //多出字数显示为省略号
                            $(".ellipsis").each(function () {
                                if ($(this).text().length > 10) {
                                    var text = $(this).text().substring(0, 10) + "...";
                                    $(this).text(text);
                                }
                            })


                        }
                    });
                }
            })

        };
    //初始化数据
    getList(pageNo, pageSize);
    //初始化帮扶开始时间
    laydate.render({
        elem: '#beginDate', //指定元素
        type: 'datetime'
    });
    //初始化帮扶结束时间
    laydate.render({
        elem: '#endDate', //指定元素
        type: 'datetime'
    });
    // 流程
    main.on('click', '.queryBtn', function () { //查询
        var num = 2;
        $('.time').each(function () {
            if ($(this).val() == '') { //开始时间和结束时间必须同时有或者同时没有
                num--
            }
        })
        if (num == 1) { //开始或结束时间没有
            layer.msg('请选择开始和结束时间')
        } else {
            //判断结束时间小于开始时间
            if ($("#endDate").val() < $("#beginDate").val()) {
                layer.msg("结束时间需要大于开始时间！")
                return false
            }
            getList(pageNo, pageSize, 'true')
        }

    });
    main.on('click', '.export_btn ', function () { //导出
        var num = 2;
        $('.time').each(function () {
            if ($(this).val() == '') { //开始时间和结束时间必须同时有或者同时没有
                num--
            }
        })
        if (num == 1) { //开始或结束时间没有
            layer.msg('请选择开始和结束时间')
        } else {
            location.href = "visitRecd/exportVisitRecd?" + $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&poorFamily.id=" + poorFamilyId
        }
    });
    main.on('click', '.add_btn', function () { //新增
        mccms.goTo("visitingRecord", "visitingRecordEdit", {"poorFamilyId": poorFamilyId});
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parents('td').attr('pid');
        mccms.goTo("visitingRecord", "visitingRecordEdit", {"id": id, "operated": 1, "poorFamilyId": poorFamilyId});
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $(this).parents('td').attr('pid');
        mccms.goTo("visitingRecord", "visitingRecordEdit", {"id": id, "operated": 0, "poorFamilyId": poorFamilyId});
    });
    main.on('click', '.del_btn', function () { //删除
        var id = $(this).parent().attr('pid');
        mccms.operation({
            "method": "POST",
            "name": '删除',
            "url": "/visitRecd/deleteVisitRecd",
            "data": {
                "id": id
            },
            "sub": true,
            "cache": false,
            "fn": function () {
                layer.msg('删除成功！')
                getList(pageNo, pageSize, 'true')
            }
        })
    })


    $("#goBackHelp").on('click', function () { //返回
        mccms.goTo("visitingRecord", "povertyStrickenMng")
        sessionStorage.setItem("backId", "1")
    })


}

//帮扶记录新增、编辑、查看
function visitingRecordEdit() {
    var accessoryUrl = ""; //拼接路径
    var i = 0; //计数器
    var id = mccms.getHash('id'), //用户id
        poorFamilyId = mccms.getHash('poorFamilyId'), //贫困户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        form = $('#editForm'),
        path = $('.c-primary'),
        setNoticeToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/visitRecd/getVisitRecd?id=" + id,
                "cache": false,
                "method": "POST",
                success: function (data) {
                    var data = data || {
                        result: {}
                    };
                    data.result.detail = operated,
                        setForm(data.result);
                }
            })
        },
        setAddToForm = function () {
            setForm();
            $('.c-primary').text("新增帮扶记录")
        },
        setForm = function (data) { //填充表单
            //展示已上传的文件路径
            if (id) { //查看、编辑状态下执行
                var accessoryUrl = data.accessoryUrl;
                var str = accessoryUrl.split(",");
                data.str = str;
            }

            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "editList",
                "container": form,
                "data": data,
                "callback": function () {
                    $('#poorFamilyId').val(poorFamilyId)
                    //初始化时间
                    laydate.render({
                        elem: '#year', //指定元素
                        type: 'datetime'
                    });
                    var txt = operated ? '查看帮扶记录' : '编辑帮扶记录';
                    $('.c-primary').text(txt)

                    $('#file').change(function () {
                        fileUploadWay();
                    })

                    //绑定删除文件
                    delUrl();

                    //下载功能
                    $(".h_url_list .upload_btn").each(function () {
                        $(this).on("click", function () {
                            var downloadUrl = $(this).siblings("input").val();
                            location.href = "visitRecd/downloadAttachment?url=" + downloadUrl.substring(1, downloadUrl.length);
                        })
                    })

                }
            })

            //隐藏删除按钮
            if (operated == 1) {
                $(".del_btn").remove();
            }
        },

        subMsg = function (ele) { //提交用户数据
            // var num = $('.h_url_list .url').length
            // if (num == 0) {
            //     layer.msg("请至少上传一个附件")
            //     return false;
            // }
            if (id) {
                $("#useId").attr("name", "id").val(id); //编辑需增加id字段
            }

            $('.url').each(function (index) { //拼接附近路径
                if (index == $(".url").length - 1) {
                    accessoryUrl += $(this).val()
                } else {
                    accessoryUrl += $(this).val() + ",";
                }
            });
            $('#accessoryUrl').val(accessoryUrl);

            //收集参数
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/visitRecd/editVisitRecd" : "/visitRecd/addVisitRecd"; //前者编辑API，后者新增API
            valid &&
            mccms.ajax({
                "url": url,
                "data": data,
                "lock": true,
                "method": "POST",
                "success": function () {
                    layer.msg("保存成功！");
                    mccms.goTo("visitingRecordEdit", "visitingRecord", {"poorFamilyId": poorFamilyId}); //保存成功返回
                }
            })
        },
        delUrl = function (ele) {
            $('.del_btn').off().on("click", function () {
                $(this).parent('div').remove()
                //清除file里的值
                var file = document.getElementById('file');
                file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值

            })
        },
        fileUploadWay = function () {
            var uploadElm = $("#file");
            $("#mainContainer img.loadFile").remove();
            uploadElm.after('<img class="loadFile" style="width: 100px;height: 7px;display:none" src="img/loadFile.gif" alt="正在上传">');

            $("img.loadFile").show();
            $.ajaxFileUpload({
                url: mccms.domain[0] + '/base/fileUpload', //用于文件上传的服务器端请求地址
                type: 'post',
                secureuri: false, //是否需要安全协议，一般设置为false
                fileElementId: 'file', //文件上传域的IDS
                dataType: 'json',
                success: function (data, xhr, jqXHR) //服务器成功响应处理函数
                {
                    $("img.loadFile").hide();
                    layer.msg("上传文件成功！");
                    //询问是否进行导入
                    var url = data.result;
                    //显示上传的文件名
                    i++;
                    var $html = '<div class="row cl inline-block row2 url-div w-550">' +
                        '<label for="ipt2 " class="w-label">附件:&nbsp;</label>' +
                        '<input type="text"  class="input-text w-300 url url_' + i + '" name="accessoryUrl" disabled="disabled" value=' + url + ' />' +
                        '<a for="ipt2 " class="del_btn" onclick="delUrl()">删除</a>' +
                        '<a class="upload_btn"></a>'
                    '</div>';
                    $('.h_url_list').append($html)
                    $('.url_' + i).val(url) //显示上传路径
                    $('.url-' + i).val(url) //要上传的文件路径
                    //清除file里的值
                    var file = document.getElementById('file');
                    //file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值

                    //绑定删除文件
                    delUrl();
                    $('#file').change(function () {
                        fileUploadWay();
                    })


                },
                error: function (data, status, e) //服务器响应失败处理函数
                {
                    alert(e)
                }
            })

        };


    // 流程
    id ? setNoticeToForm() : setAddToForm();
    form.on('click', '.sub_btn', function () {
        //myRequired("editForm", "popup"); //必填提示
        subMsg($(this));
    });

    $('#goToBack').click(function () { //返回
        mccms.goTo('visitingRecordEdit', "visitingRecord", {"poorFamilyId": poorFamilyId}); //返回
    })


}


/*  Devin 2017-11-28
 *  统计报表模板
 *  dataUrl 数据查询接口
 *  exportUrl 数据导出接口
 */
function statisticsList(dataUrl, exportUrl) {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            areaSelected(cryVal, nameVal, checkType, function () { //areaSelected() 权限控制方法
                mccms.ajax({ //贫困户学生查询API
                    "url": dataUrl,
                    "cache": false,
                    "method": "POST",
                    "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "mainList",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);

                                //点击数据项添加背景色
                                tdAddBg('table')

                                //获取乡下拉选中值编码
                                areaCodeInquire("cry")
                                //乡回显
                                $('#cry').change(function (event) {
                                    /* Act on the event */
                                    cryVal = $(this).find('option:selected').val() //获取乡选择，用于查询条件回显，若不获取，条件会被重置
                                })

                            }
                        });
                    }
                })
            });
        };
    ThisYear(); //备份当前年

    //初始化年度时间
    laydate.render({
        elem: '#year', //指定元素
        type: 'year', //年选择器
    })
    // 流程
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')
    });
    main.on('click', ".export_btn", function () {
        location.href = exportUrl + "?" + $("#searchForm").serialize();
    });
    //初始化数据
    getList(pageNo, pageSize);
}

/*乡镇下拉获取areaCode查询*/
function areaCodeInquire(idName) {
    //获取乡下拉选中值
    $('#' + idName).change(function (event) {
        /* Act on the event */
        var cryCode = $(this).find("option:checked").attr("data-number");
        $('#h-' + idName).val(cryCode);
    });
}

/*
    车管所管理
   Devin
   2017-12-5
*/
function carManage() {

    // 变量声明
    var main = $('#MainList'),
        addMain = $('#addPopup'),
        modelForm = $('#modelForm'),
        memberArr = [],
        operated = 0,
        detail = 0,
        isEdit = 0,
        village1Id = null,
        _id = null,
        addTime = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        urlStr = "&cry=" + s_cry + "&name=" + s_name,
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        // id ：操作记录的id
        // operated 0为返贫，1为脱贫
        changePop = function (id, operated) {
            layer.open({
                type: 1,
                area: ['530px', '500px'],
                title: '变更情况',
                shade: 0.5,
                moveType: 1,
                shift: 0,
                content: $('.change-box'),
                success: function () {
                    //form-change
                    var myDate = new Date();
                    $("#change-date").val(myDate.toLocaleDateString());
                    $("#changes-type").val(operated);
                    $("#reason").val("");
                    $(".input-btn", ".change-box").off().on('click', function () {
                        $("#changes-type").removeAttr("disabled");

                        var index = layer.index;
                        mccms.ajax({
                            //"url": "/naorpo/updatePoor",
                            "url": "/ridPo/addRidPoor",
                            "cache": false,
                            "method": "POST",
                            "data": $("#form-change").serialize() + "&pid=" + id,
                            "success": function (data) {
                                layer.close(index);
                                layer.msg('操作成功！')
                                getList(no, size)
                            }
                        })
                    })
                }
            })
        },
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({
                    "url": "/poorFa/queryPoorFamily",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        //乡选中加载村数据
                        $("#cry").change(function () {
                            cryId = $(this).find("option:checked").attr("id");
                            cryVal = $(this).find("option:checked").val();
                            $("#h-cry").val($(this).find("option:checked").attr("data-number"))
                            $("#h-name").val("") //清空村值
                            mccms.ajax({
                                "url": "/area/findarea",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "fatherId": cryId
                                },
                                success: function (data) {
                                    var naturalsHtml = '<option value="" selected>请选择</option>';
                                    for (var i = 0; i < data.result.length; i++) {
                                        naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                    }
                                    $("#name").html(naturalsHtml);


                                }
                            });
                        });


                        //村选中加载村数据
                        $("#name").change(function () {
                            nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
                            s_name_id = $(this).find("option:checked").attr("data-number");
                            $('#h-name').val(s_name_id)
                        });


                        mccms.getHbs({
                            "local": true,
                            "hbsName": "list1",
                            "container": $("#tbody1"),
                            "data": data.result,
                            "callback": function () {
                                //回显
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == "cry") {
                                            $('#cry option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    /* $("#h-cry").val($(this).attr("data-number")) //乡code值回显*/
                                                }
                                            })
                                            cryVal = prevFrom[i] //乡赋值，用于分页点击之后回显
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            $('#name option').each(function () {
                                                if ($(this).val() == prevFrom[i]) {
                                                    $(this).attr('selected', 'selected')
                                                    /*$("#h-name").val($(this).attr("data-number")) //村code值回显*/
                                                }
                                            })
                                            nameVal = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");


                                //点击数据项添加背景色 
                                tdAddBg('tbody1')

                                //10-14 kb add
                                //选择年度
                                laydate.render({
                                    elem: '#year', //指定元素
                                    type: 'year'
                                });
                                //脱贫
                                $(".outPoor_btn").unbind("click");
                                $('.outPoor_btn').on('click', function () {
                                    //脱贫时改变value与text
                                    $("#changes-type .outinPoor").val("已脱贫").text("脱贫");

                                    var checkedNum = $("#form1").find("input[type=checkbox]:checked").length;
                                    if (checkedNum == 1) {
                                        var id = $("#form1").find("input[type=checkbox]:checked").val()
                                        changePop(id, 1)
                                    } else if (checkedNum < 1) {
                                        layer.msg("请选择一户贫困户")
                                        return false
                                    } else if (checkedNum > 1) {
                                        layer.msg("不能同时选择多个贫困户")
                                        return false
                                    }

                                })
                                //返贫
                                $(".inPoor_btn").unbind("click");
                                $('.inPoor_btn').on('click', function () {
                                    //脱贫时改变value与text
                                    $("#changes-type .outinPoor").val("未脱贫").text("返贫");

                                    var checkedNum = $("#form1").find("input[type=checkbox]:checked").length;
                                    if (checkedNum == 1) {
                                        var id = $("#form1").find("input[type=checkbox]:checked").val()
                                        changePop(id, 0)
                                    } else if (checkedNum < 1) {
                                        layer.msg("请选择一户贫困户")
                                        return false
                                    } else if (checkedNum > 1) {
                                        layer.msg("不能同时选择多个贫困户")
                                        return false
                                    }

                                })
                            }
                        });
                    }
                })
            });
        },
        getW = function (params) {
            //省请求
            _ajaxW(0, function (data) {
                createOption(data, function (cryHtml) {
                    $(".province1").each(function (i, item) {
                        $(item).html(cryHtml)
                    })
                    //省判断选中
                    $('.province1').val(s_province)
                    if (s_province) {
                        $('#province1').attr('disabled', 'disabled')
                    }
                    //市请求
                    _ajaxW(1, function (data) {
                        createOption(data, function (cryHtml) {
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                            //市判断选中
                            $('.city').val(s_city)
                            if (s_city) {
                                $('#city1').attr('disabled', 'disabled')
                            }
                            //县请求
                            _ajaxW(2, function (data) {
                                createOption(data, function (cryHtml) {
                                    $(".county").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                    //县判断选中
                                    $('.county').val(s_cty)
                                    if (s_cty) {
                                        $('#county').attr('disabled', 'disabled')
                                    }
                                    //乡请求
                                    _ajaxW(3, function (data) {
                                        createOption(data, function (cryHtml) {
                                            $('#country').html(cryHtml)
                                            $('#country').val(s_cry)


                                            //村请求
                                            if (s_cry) {
                                                $('#country').attr('disabled', 'disabled')
                                            }
                                            if (params) {
                                                $('#province1').val(params.province)
                                                $('#city1').val(params.city)
                                                $('#county').val(params.county)
                                                $('#country').val(params.country)
                                            }
                                            var countryId = $('#country').find('option:checked').attr('id');
                                            if (params) {
                                                // s_cry_id = countryId
                                            }
                                            _ajaxW(s_cry_id, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                                $('#village1').val(s_name)
                                                if (s_name) {
                                                    $('#village1').attr('disabled', 'disabled')
                                                }
                                                if (params) {
                                                    $("#village1").val(params.village);
                                                }
                                                //村下拉
                                                $("#village1").change(function () {
                                                    village1Id = $(this).find("option:checked").attr("id");
                                                });
                                            })
                                        })
                                    })
                                    if (s_cry) {
                                        $('#country').attr('disabled', 'disabled')
                                    } else {
                                        //乡下拉
                                        $("#country").change(function () {
                                            var countryId = $(this).find("option:checked").attr("id");
                                            //村请求
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                            })
                                        });
                                    }
                                })
                            })
                        })
                    })
                })

                //省下拉
                $(".province1").change(function () {
                    var province1Id = $(this).find("option:checked").attr("id");
                    //市请求
                    _ajaxW(province1Id, function (data) {
                        createOption(data, function (cryHtml) {
                            // $("#city").html(cryHtml);
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                        })
                    })
                    //市下拉
                    $(".city").change(function () {
                        var cityId = $(this).find("option:checked").attr("id");
                        //县请求
                        _ajaxW(cityId, function (data) {
                            createOption(data, function (cryHtml) {
                                // $("#county").html(cryHtml);
                                $(".county").each(function (i, item) {
                                    $(item).html(cryHtml)
                                })
                            })
                        })
                        //县下拉
                        $(".county").change(function () {
                            var countyId = $(this).find("option:checked").attr("id");
                            //乡请求
                            _ajaxW(countyId, function (data) {
                                createOption(data, function (cryHtml) {
                                    // $("#country").html(cryHtml);
                                    $(".country").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                })
                            })
                            //乡下拉
                            $("#country").change(function () {
                                var countryId = $(this).find("option:checked").attr("id");

                                //村请求
                                _ajaxW(countryId, function (data) {
                                    createOption(data, function (cryHtml) {
                                        $("#village1").html(cryHtml);
                                    })
                                })

                                //村下拉
                                $("#village1").change(function () {
                                    village1Id = $(this).find("option:checked").attr("id");
                                });
                            });
                        });
                    });
                });
            })
        },
        _ajaxW = function (id, fn) {
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": id
                },
                success: function (data) {
                    return fn(data)
                }
            });
        },
        createOption = function (data, fn) {
            var cryHtml = '<option value="">请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
            }
            return fn(cryHtml)
        }

    // 流程
    ThisYear(); //当前年
    main.on('click', '.add_btn', function () { //新增
        mccms.goTo("povertyStrickenMng", "povertyStrickenEdit");
    })
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parent().attr('id'); //用户ID
        mccms.goTo("carManage", "carCondition", {"id": id, "operatedState": 1, "detail": 1}); //operatedState==1为查看不可编辑,0为可编辑

    })
    main.on('click', '.edit_btn', function () { //编辑
        id = $(this).parent().attr('id'); //用户ID
        mccms.goTo("carManage", "carCondition", {
            "id": id,
            "operatedState": 1,
            "detail": 1,
            "isEdit": 1,
            "addTime": addTime
        });
    })
    main.on('click', ".interview_btn", function () { //帮扶
        var poorFamilyId = $(this).parent().attr('id'); //用户ID
        mccms.goTo("povertyStrickenMng", "visitingRecord", {"poorFamilyId": poorFamilyId,});
    })
    //删除
    main.on('click', '.del_btn', function () {
        var id = $(this).parent().attr('id');
        mccms.operation({
            "method": "POST",
            "name": '删除',
            "url": "/poorFa/deletePoorFamily",
            "data": {
                "id": id
            },
            "sub": true,
            "fn": function () {
                layer.msg('删除成功！')
                getList(no, size);
            } //确定后刷新页面
        })
    })
    main.on('click', '.queryBtn', function () { //查询
        no = 1;
        getList(pageNo, pageSize, 'true')
    });


    //从编辑、查看页面返回，查询显示原先的查询结果
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val(),
            prevFrom = {
                "cry": $('#cry').val(),
                "h-cry": $('#h-cry').val(),
                "h-name": $('#h-name').val(),
                "name": $('#name option:selected').text(),
                "year": $('#year').val(),
                "poverty": $('#poverty').val(),
                "attribute": $('#attribute').val(),
                "poorName": $('#poorName').val(),
                "idNumber": $('#idNumber').val(),
                "relation": $('#relation').val()
            };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))
    })

    getList(pageNo, pageSize);
}

function carCondition() {

    // 变量声明
    var id = mccms.getHash('id'), //用户id
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        operatedState = parseInt(mccms.getHash('operatedState')),
        detail = mccms.getHash('detail'),
        isEdit = mccms.getHash('isEdit'), //编辑状态
        addTime = sessionStorage.addTime; //使用H5本地储存获取时间

    var main = $('#MainList'),
        addMain = $('#addPopup'),
        modelForm = $('#modelForm'),
        memberArr = [],
        operated = 0,
        village1Id = null,
        size = 10,
        no = 1,
        pageCount = null,
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //村的选中
        urlStr = "&cry=" + s_cry + "&name=" + s_name,
        // id ：操作记录的id
        // operated 0为返贫，1为脱贫

        getDetail = function (id) { //新增、查看、编辑方法 刷新页面
            if (!id) { //新增-页面
                //渲染主页面,但没填充数据
                mccms.getHbs({
                    "local": true,
                    "hbsName": "info",
                    "container": $("#addPopup"),
                    "data": {
                        operated: 1
                    },
                    "callback": function () {
                        modelForm = $('#modelForm')
                        modelForm.mcFormValide(); //绑定表单验证
                        getW()
                        //nav条定位锚点
                        scrollToBox("nav-item")

                        //家庭成员重置按钮
                        $("#modelForm .reset-btn").on("click", function () {
                            mccms.getHbs({ //家庭成员模板
                                "local": true,
                                "hbsName": "memberForm",
                                "container": $("#modelForm1"),
                                "data": {},
                                "callback": function () {
                                    laydate.render({ //出生日期
                                        elem: '#birthTime'
                                    });
                                    laydate.render({ //入学时间
                                        elem: '#enterTime'
                                    });
                                }
                            })
                        })

                        //家庭成员新增按钮
                        $("#modelForm #addMember-btn").on("click", function () {
                            var checkboxMember = $('.checkbox-member input:checked')
                            if (checkboxMember.length) {
                                layer.msg('新增时不能勾选家庭成员')
                                return false
                            }
                            $("#addFamilyMask").show();
                            $('#mainContainer').addClass('noScroll');

                            mccms.getHbs({ //家庭成员弹窗
                                "local": true,
                                "hbsName": "memberForm",
                                "container": $("#modelForm1"),
                                "data": {},
                                "callback": function () {
                                    laydate.render({ //出生日期
                                        elem: '#birthTime'
                                    });
                                    laydate.render({ //上年务工时间
                                        elem: '#workTime'
                                    });
                                    laydate.render({ //入学时间
                                        elem: '#enterTime'
                                    });

                                    //身份证读取
                                    function ClearIDCard() {
                                        CVR_IDCard.Name = "";
                                        CVR_IDCard.NameL = "";
                                        CVR_IDCard.Sex = "";
                                        CVR_IDCard.SexL = "";
                                        CVR_IDCard.Nation = "";
                                        //CVR_IDCard.NationL="";
                                        CVR_IDCard.Born = "";
                                        //CVR_IDCard.BornL="";
                                        CVR_IDCard.Address = "";
                                        CVR_IDCard.CardNo = "";
                                        CVR_IDCard.Police = "";
                                        CVR_IDCard.Activity = "";
                                        CVR_IDCard.NewAddr = "";

                                        return true;
                                    }

                                    function ReadIDCard() {
                                        CVR_IDCard.PhotoPath = 'C:\\'
                                        CVR_IDCard.TimeOut = 3;
                                        ClearIDCard();
                                        // return true;
                                    }

                                    $("#readyCard-btn").unbind("click");
                                    $('#readyCard-btn').on('click', function () {
                                        ReadIDCard()
                                        var State = CVR_IDCard.GetState;
                                        var strReadResult = CVR_IDCard.ReadCard;
                                        if (State !== '0') {
                                            layer.msg('请插入设备')
                                            return false
                                        }
                                        if (strReadResult !== '0') {
                                            layer.msg('请检查是否正常放置了身份证！')
                                            return false
                                        }
                                        if (CVR_IDCard.Sex === '1') {
                                            $('#sex').val('男')
                                        } else {
                                            $('#sex').val('女')
                                        }
                                        $('#name1').val(CVR_IDCard.NameL)
                                        $('#idNumber').val(CVR_IDCard.CardNo)
                                        $('#birthTime').val(CVR_IDCard.BornL)

                                    })

                                }
                            });
                        })

                        //家庭成员删除按钮
                        $('#deleteMember-btn').on('click', function () {
                            var checkboxMember = $('.checkbox-member input:checked')
                            if (!checkboxMember.length) {
                                layer.msg('请勾选家庭成员')
                                return false
                            }
                            var checkArr = []
                            checkboxMember.each(function (i, item) {
                                checkArr.push($(item).attr('id'))
                            })
                            mccms.ajax({ //删除家庭成员API
                                "url": "/poorFa/deleteFamilyid",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    sid: checkArr.join(',')
                                },
                                "success": function (data) {
                                    layer.msg('删除成功')
                                    //刷新
                                    getMemberList();
                                }
                            })
                        })


                        //家庭成员编辑按钮
                        $('#modelForm #editMember-btn').on('click', function () {
                            $("#addFamilyMask #div1").text("编辑家庭成员")
                            var checkboxMember = $('.checkbox-member input:checked') //被勾选家庭成员
                            var familyMemberId = checkboxMember.attr("id"); //被勾选家庭成员id
                            if (!checkboxMember.length) {
                                layer.msg('请勾选家庭成员')
                                return false
                            }
                            if (checkboxMember.length > 1) {
                                layer.msg('只能单个修改')
                                return false
                            }

                            $("#addFamilyMask").show(); //家庭成员的弹窗
                            $('#mainContainer').addClass('noScroll');

                            //请求单个家庭成员数据
                            mccms.ajax({ //查询单个家庭成员API
                                "url": "/poorFa/findFamily",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "sid": familyMemberId
                                },
                                success: function (data) {
                                    mccms.getHbs({ //家庭成员弹窗
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": data.result[0],
                                        "callback": function () {
                                            laydate.render({ //出生日期
                                                elem: '#birthTime'
                                            });
                                            laydate.render({ //上年务工时间
                                                elem: '#workTime'
                                            });
                                            laydate.render({ //入学时间
                                                elem: '#enterTime'
                                            });

                                            //身份证读取
                                            function ClearIDCard() {
                                                CVR_IDCard.Name = "";
                                                CVR_IDCard.NameL = "";
                                                CVR_IDCard.Sex = "";
                                                CVR_IDCard.SexL = "";
                                                CVR_IDCard.Nation = "";
                                                //CVR_IDCard.NationL="";
                                                CVR_IDCard.Born = "";
                                                //CVR_IDCard.BornL="";
                                                CVR_IDCard.Address = "";
                                                CVR_IDCard.CardNo = "";
                                                CVR_IDCard.Police = "";
                                                CVR_IDCard.Activity = "";
                                                CVR_IDCard.NewAddr = "";

                                                return true;
                                            }

                                            function ReadIDCard() {
                                                CVR_IDCard.PhotoPath = 'C:\\'
                                                CVR_IDCard.TimeOut = 3;
                                                ClearIDCard();
                                                // return true;
                                            }

                                            $("#readyCard-btn").unbind("click");
                                            $('#readyCard-btn').on('click', function () {
                                                ReadIDCard()
                                                var State = CVR_IDCard.GetState;
                                                var strReadResult = CVR_IDCard.ReadCard;
                                                if (State !== '0') {
                                                    layer.msg('请插入设备')
                                                    return false
                                                }
                                                if (strReadResult !== '0') {
                                                    layer.msg('请检查是否正常放置了身份证！')
                                                    return false
                                                }
                                                if (CVR_IDCard.Sex === '1') {
                                                    $('#sex').val('男')
                                                } else {
                                                    $('#sex').val('女')
                                                }
                                                $('#name1').val(CVR_IDCard.NameL)
                                                $('#idNumber').val(CVR_IDCard.CardNo)
                                                $('#birthTime').val(CVR_IDCard.BornL)

                                            })
                                        }
                                    })
                                }
                            })


                        })


                        //关闭弹窗
                        $('.close-btn').on('click', function () {
                            $("#addFamilyMask").hide();
                            $('#mainContainer').removeClass('noScroll')
                        })

                        /*帮扶责任人模块 start*/
                        //帮扶责任人新增按钮
                        $("#addPersons-btn").on("click", function () {
                            if ($("input[name='name']")) { //村级别时直接获取村的id
                                village1Id = $("#village1").find("option:selected").attr("id");
                            }
                            if (!village1Id) {
                                layer.msg("请选择行政村！");
                                return false;
                            }
                            layer.open({
                                type: 1,
                                title: "帮扶责任人结对信息",
                                area: ['80%', '60%'], //宽高
                                content: $("#jieduiPopup"),
                                success: function () {
                                    mccms.ajax({ //村 查找对应 帮扶责任人结对信息API
                                        "url": "/helppeson/getHelpPersonByAreaId",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            areaId: village1Id, //村的id
                                            pageSize: 10,
                                            pageNo: 1
                                        },
                                        "success": function (data) {
                                            if (data.result) {
                                                mccms.getHbs({
                                                    "local": true,
                                                    "hbsName": "addHelpList",
                                                    "container": $("#addHelpTobdy"),
                                                    "data": data,
                                                    "callback": function () {
                                                        mccms.pageHtml(data, getHelpPersonList, ''); //分页
                                                        //标记已选择的责任人
                                                        var personChecked = $("#helpTobdy input[name=help]"); //主页面-已选择责任人
                                                        var addPersonAll = $("#addHelpTobdy input[name=addHelp]"); //弹窗页面-所有责任人
                                                        personChecked.each(function (item) {
                                                            item = $(this).attr("id");
                                                            $('#addHelpTobdy input[id=' + item + ']').attr("checked", "checked")
                                                        })

                                                    }
                                                });
                                            } else {
                                                mccms.getHbs({
                                                    "local": true,
                                                    "hbsName": "addHelpList",
                                                    "container": $("#addHelpTobdy"),
                                                    "data": '',
                                                    "callback": function () {
                                                    }
                                                });
                                            }
                                        }
                                    })


                                }


                            })
                        })
                        //帮扶责任人保存按钮
                        $("#keepPersons-btn").on("click", function () {
                            //帮扶责任人多选
                            var helpArr = $('#addHelpTobdy input[name=addHelp]:checked')
                            var arr1 = []; //帮扶责任人id数组
                            if (helpArr.length == 0) {
                                layer.msg("请先勾选帮扶责任人！")
                                return false
                            }
                            if (helpArr.length) {
                                helpArr.each(function (i, item) {
                                    arr1.push($(item).attr('id'))
                                })
                            }
                            layer.closeAll(); //关闭弹窗
                            var sid = arr1 ? arr1.join(',') : ''
                            getHelpPersonList(sid);

                        })
                        //帮扶责任人删除按钮
                        $("#deletePersons-btn").on("click", function () {
                            //帮扶责任人多选
                            var allHelpArr = $('#helpTobdy input[name=help]'); //所有责任人
                            var helpArr = allHelpArr.not(":checked"); //非选定状态责任人
                            var helpArred = $('#helpTobdy input[name=help]:checked'); //选定状态责任人
                            if (helpArred.length == 0) {
                                layer.msg("请先勾选帮扶责任人！")
                                return false
                            }
                            if (allHelpArr.length == 1 || allHelpArr.length == helpArred.length && helpArred) { //剩余一个责任人 或 删除全部时,清空表格
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "helpList",
                                    "container": $("#helpTobdy"),
                                    "data": '',
                                    "callback": function () {
                                        layer.msg("删除成功！")
                                    }
                                });

                            } else { //剩余多个责任人时
                                var arr1 = []; //责任人id数组
                                if (helpArr.length) {
                                    helpArr.each(function (i, item) {
                                        arr1.push($(item).attr('id'))
                                    })
                                }

                                var sid = arr1 ? arr1.join(',') : ''
                                getHelpPersonList(sid, true);
                            }

                        })

                        //帮扶责任人取消按钮
                        $("#cancelPersons-btn").on("click", function () {
                            layer.closeAll(); //关闭弹窗
                        })

                        /*帮扶责任人模块 end*/

                    }
                })
                return false;
            }

            //查看与编辑页面
            mccms.ajax({ //贫困户详情API - 参数: 贫困户id 
                "url": "/poorFa/getPoorFamily",
                "cache": false,
                "method": "POST",
                "data": {
                    "id": id
                },
                "success": function (data) {
                    // 改造填充数据
                    data.result.poorFamily.operated = operated
                    data.result.poorFamily.detail = detail
                    data.result.poorFamily.operatedState = operatedState; //operatedState==1为查看不可编辑,0为可编辑

                    mccms.getHbs({ //填充表单
                        "local": true,
                        "hbsName": "info", //主模板
                        "container": $("#addPopup"), //主页面
                        "data": data.result.poorFamily,
                        "callback": function () {
                            //点位锚点
                            scrollToBox("nav-item")

                            //查看状态时,删除掉家庭成员的"新增、删除、编辑"三个按钮
                            if (data.result.poorFamily.operatedState == 1) {
                                $(".poverty-btnGroup").remove();
                                $("nav .c-primary").html("编辑贫困户");
                            }
                            /* //修改模块名称-编辑
                             if (data.result.poorFamily.operatedState == 0) {
                                 $("nav .c-primary").html("编辑贫困户");
                             }
                             //修改模块名称
                             if (inquire == 1) { //inquire == 1从《账表查询》过来则修改模块名称
                                 $("nav .menuLevel1").html("账表查询");
                                 $("nav .menuLevel2").html("贫困户查询");
                                 $("nav .c-primary").html("查看贫困户");
                             }*/

                            //填充省市区乡村值
                            getW({
                                province: data.result.poorFamily.province,
                                city: data.result.poorFamily.city,
                                county: data.result.poorFamily.county,
                                country: data.result.poorFamily.country,
                                village: data.result.poorFamily.village
                            })

                            //填充其他致贫原因
                            var otherArr = data.result.poorFamily.other ? data.result.poorFamily.other.split(',') : ''
                            if (otherArr) {
                                for (var i = 0; i < otherArr.length; i++) {
                                    $('#other input').each(function (j, item) {
                                        if (item.value === otherArr[i]) {
                                            $(item).prop('checked', true)
                                        }
                                    })
                                }
                            }

                            modelForm = $('#modelForm'); //主模板表单
                            modelForm.mcFormValide(); //绑定表单验证

                            //填充家庭成员列表
                            mccms.getHbs({
                                "local": true,
                                "hbsName": "list",
                                "container": $("#tbody"),
                                "data": {
                                    result: data.result.poorFamily.family
                                }
                            });

                            //新增、删除、编辑按钮组
                            if (isEdit) { //isEdit==1表示编辑页面
                                //家庭成员重置按钮
                                $("#modelForm .reset-btn").on("click", function () {
                                    mccms.getHbs({ //家庭成员模板
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": {}
                                    })
                                })

                                //家庭成员新增按钮
                                $("#modelForm #addMember-btn").on("click", function () {
                                    var checkboxMember = $('.checkbox-member input:checked')
                                    if (checkboxMember.length) {
                                        layer.msg('新增时不能勾选家庭成员')
                                        return false
                                    }
                                    $("#addFamilyMask").show();
                                    $('#mainContainer').addClass('noScroll');

                                    mccms.getHbs({ //家庭成员弹窗
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": {},
                                        "callback": function () {
                                            laydate.render({ //出生日期
                                                elem: '#birthTime'
                                            });
                                            laydate.render({ //上年务工时间
                                                elem: '#workTime'
                                            });
                                            laydate.render({ //入学时间
                                                elem: '#enterTime'
                                            });

                                            //身份证读取
                                            function ClearIDCard() {
                                                CVR_IDCard.Name = "";
                                                CVR_IDCard.NameL = "";
                                                CVR_IDCard.Sex = "";
                                                CVR_IDCard.SexL = "";
                                                CVR_IDCard.Nation = "";
                                                //CVR_IDCard.NationL="";
                                                CVR_IDCard.Born = "";
                                                //CVR_IDCard.BornL="";
                                                CVR_IDCard.Address = "";
                                                CVR_IDCard.CardNo = "";
                                                CVR_IDCard.Police = "";
                                                CVR_IDCard.Activity = "";
                                                CVR_IDCard.NewAddr = "";

                                                return true;
                                            }

                                            function ReadIDCard() {
                                                CVR_IDCard.PhotoPath = 'C:\\'
                                                CVR_IDCard.TimeOut = 3;
                                                ClearIDCard();
                                                // return true;
                                            }

                                            $("#readyCard-btn").unbind("click");
                                            $('#readyCard-btn').on('click', function () {
                                                ReadIDCard()
                                                var State = CVR_IDCard.GetState;
                                                var strReadResult = CVR_IDCard.ReadCard;
                                                if (State !== '0') {
                                                    layer.msg('请插入设备')
                                                    return false
                                                }
                                                if (strReadResult !== '0') {
                                                    layer.msg('请检查是否正常放置了身份证！')
                                                    return false
                                                }
                                                if (CVR_IDCard.Sex === '1') {
                                                    $('#sex').val('男')
                                                } else {
                                                    $('#sex').val('女')
                                                }
                                                $('#name1').val(CVR_IDCard.NameL)
                                                $('#idNumber').val(CVR_IDCard.CardNo)
                                                $('#birthTime').val(CVR_IDCard.BornL)

                                            })
                                        }
                                    });
                                })

                                //家庭成员删除按钮
                                $('#deleteMember-btn').on('click', function () {
                                    var checkboxMember = $('.checkbox-member input:checked')
                                    if (!checkboxMember.length) {
                                        layer.msg('请勾选家庭成员')
                                        return false
                                    }
                                    var checkArr = []
                                    checkboxMember.each(function (i, item) {
                                        checkArr.push($(item).attr('id'))
                                    })
                                    mccms.ajax({ //删除家庭成员API
                                        "url": "/poorFa/deleteFamilyid",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            sid: checkArr.join(',')
                                        },
                                        "success": function (data) {
                                            layer.msg('删除成功')
                                            getDetail(id); //刷新
                                        }
                                    })
                                })

                                //家庭成员编辑按钮
                                $('#modelForm #editMember-btn').on('click', function () {
                                    $("#addFamilyMask #div1").text("编辑家庭成员")
                                    var checkboxMember = $('.checkbox-member input:checked')
                                    if (!checkboxMember.length) {
                                        layer.msg('请勾选家庭成员')
                                        return false
                                    }
                                    if (checkboxMember.length > 1) {
                                        layer.msg('只能单个修改')
                                        return false
                                    }
                                    var oneData = {}; //家庭成员数据
                                    data.result.poorFamily.family.forEach(function (item) {
                                        console.log(item)
                                        if (item.id == $(checkboxMember[0]).attr('id')) {
                                            oneData = item
                                            return false
                                        }
                                    })

                                    $("#addFamilyMask").show(); //家庭成员的弹窗
                                    $('#mainContainer').addClass('noScroll');

                                    mccms.getHbs({ //家庭成员弹窗
                                        "local": true,
                                        "hbsName": "memberForm",
                                        "container": $("#modelForm1"),
                                        "data": oneData,
                                        "callback": function () {
                                            laydate.render({ //出生日期
                                                elem: '#birthTime'
                                            });
                                            laydate.render({ //上年务工时间
                                                elem: '#workTime'
                                            });
                                            laydate.render({ //入学时间
                                                elem: '#enterTime'
                                            });

                                            //身份证读取
                                            function ClearIDCard() {
                                                CVR_IDCard.Name = "";
                                                CVR_IDCard.NameL = "";
                                                CVR_IDCard.Sex = "";
                                                CVR_IDCard.SexL = "";
                                                CVR_IDCard.Nation = "";
                                                //CVR_IDCard.NationL="";
                                                CVR_IDCard.Born = "";
                                                //CVR_IDCard.BornL="";
                                                CVR_IDCard.Address = "";
                                                CVR_IDCard.CardNo = "";
                                                CVR_IDCard.Police = "";
                                                CVR_IDCard.Activity = "";
                                                CVR_IDCard.NewAddr = "";

                                                return true;
                                            }

                                            function ReadIDCard() {
                                                CVR_IDCard.PhotoPath = 'C:\\'
                                                CVR_IDCard.TimeOut = 3;
                                                ClearIDCard();
                                                // return true;
                                            }

                                            $("#readyCard-btn").unbind("click");
                                            $('#readyCard-btn').on('click', function () {
                                                ReadIDCard()
                                                var State = CVR_IDCard.GetState;
                                                var strReadResult = CVR_IDCard.ReadCard;
                                                if (State !== '0') {
                                                    layer.msg('请插入设备')
                                                    return false
                                                }
                                                if (strReadResult !== '0') {
                                                    layer.msg('请检查是否正常放置了身份证！')
                                                    return false
                                                }
                                                if (CVR_IDCard.Sex === '1') {
                                                    $('#sex').val('男')
                                                } else {
                                                    $('#sex').val('女')
                                                }
                                                $('#name1').val(CVR_IDCard.NameL)
                                                $('#idNumber').val(CVR_IDCard.CardNo)
                                                $('#birthTime').val(CVR_IDCard.BornL)

                                            })
                                        }
                                    });
                                })

                                //关闭弹窗
                                $('.close-btn').on('click', function () {
                                    $("#addFamilyMask").hide();
                                    $('#mainContainer').removeClass('noScroll')
                                })

                                /*帮扶责任人模块 start*/
                                //帮扶责任人新增按钮
                                $("#addPersons-btn").on("click", function () {
                                    if ($("input[name='name']")) { //村级别时直接获取村的id
                                        village1Id = $("#village1").find("option:selected").attr("id");
                                    }
                                    if (!village1Id) {
                                        layer.msg("请先填写家庭住址！");
                                        return false;
                                    }
                                    layer.open({
                                        type: 1,
                                        title: "帮扶责任人结对信息",
                                        area: ['80%', '60%'], //宽高
                                        content: $("#jieduiPopup"),
                                        success: function () {
                                            mccms.ajax({ //村 查找对应 帮扶责任人结对信息API
                                                "url": "/helppeson/getHelpPersonByAreaId",
                                                "cache": false,
                                                "method": "POST",
                                                "data": {
                                                    areaId: village1Id, //村的id
                                                    pageSize: 10,
                                                    pageNo: 1
                                                },
                                                "success": function (data) {
                                                    if (data.result) {
                                                        mccms.getHbs({
                                                            "local": true,
                                                            "hbsName": "addHelpList",
                                                            "container": $("#addHelpTobdy"),
                                                            "data": data,
                                                            "callback": function () {
                                                                mccms.pageHtml(data, getHelpPersonList, ''); //分页
                                                                //标记已选择的责任人
                                                                var personChecked = $("#helpTobdy input[name=help]"); //主页面-已选择责任人
                                                                var addPersonAll = $("#addHelpTobdy input[name=addHelp]"); //弹窗页面-所有责任人
                                                                personChecked.each(function (item) {
                                                                    item = $(this).attr("id");
                                                                    $('#addHelpTobdy input[id=' + item + ']').attr("checked", "checked")
                                                                })

                                                            }
                                                        });
                                                    } else {
                                                        mccms.getHbs({
                                                            "local": true,
                                                            "hbsName": "addHelpList",
                                                            "container": $("#addHelpTobdy"),
                                                            "data": '',
                                                            "callback": function () {
                                                            }
                                                        });
                                                    }
                                                }
                                            })


                                        }
                                    })
                                })
                                //帮扶责任人保存按钮
                                $("#keepPersons-btn").on("click", function () {
                                    //帮扶责任人多选
                                    var helpArr = $('#addHelpTobdy input[name=addHelp]:checked')
                                    var arr1 = []; //帮扶责任人id数组
                                    if (helpArr.length == 0) {
                                        layer.msg("请先勾选帮扶责任人！")
                                        return false
                                    }
                                    if (helpArr.length) {
                                        helpArr.each(function (i, item) {
                                            arr1.push($(item).attr('id'))
                                        })
                                    }
                                    layer.closeAll(); //关闭弹窗
                                    var sid = arr1 ? arr1.join(',') : ''
                                    getHelpPersonList(sid);

                                })
                                //帮扶责任人删除按钮
                                $("#deletePersons-btn").on("click", function () {

                                    //帮扶责任人多选
                                    var allHelpArr = $('#helpTobdy input[name=help]'); //所有责任人
                                    var helpArr = allHelpArr.not(":checked"); //非选定状态责任人
                                    var helpArred = $('#helpTobdy input[name=help]:checked'); //选定状态责任人
                                    if (allHelpArr.length == 0) {
                                        return false
                                    }
                                    if (allHelpArr.length == 1 || allHelpArr.length == helpArred.length && helpArred) { //剩余一个责任人 或 删除全部时,清空表格
                                        mccms.getHbs({
                                            "local": true,
                                            "hbsName": "helpList",
                                            "container": $("#helpTobdy"),
                                            "data": '',
                                            "callback": function () {
                                                layer.msg("删除成功！")
                                            }
                                        });

                                    } else { //剩余多个责任人时
                                        var arr1 = []; //责任人id数组
                                        if (helpArr.length) {
                                            helpArr.each(function (i, item) {
                                                arr1.push($(item).attr('id'))
                                            })
                                        }

                                        var sid = arr1 ? arr1.join(',') : ''
                                        getHelpPersonList(sid, true);
                                    }

                                })

                                //帮扶责任人取消按钮
                                $("#cancelPersons-btn").on("click", function () {
                                    layer.closeAll(); //关闭弹窗
                                })

                                /*帮扶责任人模块 end*/


                            }
                            //帮扶责任人结对信息回显
                            if (detail && !operated) {
                                mccms.getHbs({
                                    "local": true,
                                    "hbsName": "helpList",
                                    "container": $("#helpTobdy"),
                                    "data": {
                                        result: data.result.poorFamily.helpPersons
                                    },
                                    "callback": function () {
                                    }
                                });
                            }


                        }
                    });
                }
            })


        },
        getMemberList = function (id) { //家庭成员列表
            var familyUrl = id ? "/poorFa/getPoorFamily" : "/poorFa/queryFamily"; //前者表示编辑页面时API，后者表示新增页面时API
            var familyData = id ? {"id": id} : ""; //前者表示编辑页面时参数-用户id，后者表示新增页面时 参数
            mccms.ajax({ //贫困户详情API - 参数: 贫困户id  
                "url": familyUrl,
                "cache": false,
                "method": "POST",
                "data": familyData,
                "success": function (data) {
                    var resultData; //填充的数据
                    if (id) { //编辑页面时
                        data.result.poorFamily.family.forEach(function (item) { //所有家庭成员的id,用于保存到对应贫困户里
                            memberArr.push(item.id)
                        })
                        resultData = {result: data.result.poorFamily.family};
                    } else { //新增页面时
                        data.result.forEach(function (item) {
                            memberArr.push(item.id)
                        })
                        resultData = {result: data.result};
                    }

                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": resultData,
                        "callback": function () {
                        }
                    });
                }
            })
        },
        getHelpPersonList = function (sid, del) { //已选定的帮扶责任人结对信息
            mccms.ajax({ //通过责任人id数组查找帮扶责任人API
                "url": "/helppeson/findhelppesonMultiple",
                "cache": false,
                "method": "POST",
                "data": {
                    "sid": sid
                },
                "success": function (data) {
                    if (data.result) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "helpList",
                            "container": $("#helpTobdy"),
                            "data": data,
                            "callback": function () {
                                if (del) {
                                    layer.msg("删除成功！")
                                } else {
                                    layer.msg("新增成功！")
                                }
                                mccms.pageHtml(data, getHelpPersonList, '');
                            }
                        });
                    } else {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "helpList",
                            "container": $("#helpTobdy"),
                            "data": '',
                            "callback": function () {
                            }
                        });
                    }
                }
            })
        },
        subMemberMsg = function () { //家庭成员保存
            var data1 = {
                name: $('#name1').val(),
                number: $('#number').val(),
                idType: $('#idType').val(),
                addTime: $('#birthTime').val(),
                nation: $('#nation').val(),
                culture: $('#culture').val(),
                healthy: $('#healthy').val(),
                soldier: $('#soldier').val(),
                province: $('#province2').val(),
                county: $('#county').val(),
                workTime: $('#workTime').val(),
                telephone: $('#telephone').val(),
                enterTime: $('#enterTime').val(),
                institution: $('#institution').val(),
                county: $('#county2').val(),
                sex: $('#sex').val(),
                idNumber: $('#idNumber').val(),
                relation: $('#relation').val(),
                number: $('#number').val(),
                political: $('#political').val(),
                school: $('#school').val(),
                labour: $('#labour').val(),
                low: $('#low').val(),
                city: $('#city2').val(),
                village: $('#village2').val(),
                company: $('#company').val(),
                large: $('#large').val(),
                schoolName: $('#schoolName').val(),
                major: $('#major').val(),
                isStudent: $('#isStudent').val(),
                medicalInsurance: $('#medicalInsurance').val(),
                illness: $('#illness').val(),
                illnessType: $('#illnessType').val(),
                lastMedicalExpense: $('#lastMedicalExpense').val(),
                lastMedicalReimburse: $('#lastMedicalReimburse').val(),
                lastIllnessReimburse: $('#lastIllnessReimburse').val(),
                lastSelfExpense: $('#lastSelfExpense').val()
            }
            console.log(data1)
            if (id) {
                data1.fid = mccms.getHash('id'); //用户id
            }

            var checkboxMember = $('.checkbox-member input:checked') //选定的家庭成员
            if (checkboxMember.length >= 2) {
                layer.msg('只能单个修改')
                return false
            } else if (checkboxMember.length === 1) { //编辑保存时

                data1.id = checkboxMember.attr('id'); //家庭成员id
                data1.fid = checkboxMember.attr('attr-fid'); //贫困户id
                mccms.ajax({ //修改家庭成员API - 参数: 贫困户id
                    "url": "/poorFa/addOrUpdateFamily",
                    "cache": false,
                    "method": "POST",
                    "data": data1,
                    "success": function () {
                        var id = mccms.getHash('id'); //用户id
                        mccms.ajax({ //查询家庭成员API
                            "url": "/poorFa/getPoorFamily",
                            "cache": false,
                            "method": "POST",
                            "data": data1,
                            "success": function (data) {
                                $("#addFamilyMask").hide();
                                $('#mainContainer').removeClass('noScroll')

                                if (!id) { //刷新 -- 新增页面-编辑
                                    var familyM = $("#tbody input[type=checkbox]"); //家庭成员
                                    var familySid = []; //家庭成员id数组
                                    familyM.each(function () {
                                        familySid.push($(this).attr("id"))
                                    })
                                    familySid = familySid.join(",")

                                    mccms.ajax({ //家庭成员详情API - 参数sid: 家庭成员id数组  
                                        "url": "/poorFa/findFamily",
                                        "cache": false,
                                        "method": "POST",
                                        "data": {
                                            "sid": familySid
                                        },
                                        "success": function (data) {
                                            mccms.getHbs({
                                                "local": true,
                                                "hbsName": "list",
                                                "container": $("#tbody"),
                                                "data": data,
                                                "callback": function () {
                                                }
                                            });
                                        }
                                    })
                                } else { //刷新 -- 编辑页面-编辑
                                    getMemberList(id)
                                }

                            }
                        })
                    }
                })
            } else { //新增按钮-保存
                var addUrl = id ? "/poorFa/addOrUpdateFamily" : "/poorFa/addFamily"; //前者编辑页面时的新增按钮，后者新增页面时的新增按钮
                mccms.ajax({ //新增与修改家庭成员API - 参数: 贫困户id
                    "url": addUrl,
                    "cache": false,
                    "method": "POST",
                    "data": data1,
                    "success": function () {
                        //关闭弹窗
                        $("#addFamilyMask").hide();
                        $('#mainContainer').removeClass('noScroll')

                        //家庭成员列表刷新
                        getMemberList(id)
                    }
                })
            }
        },
        subMsg = function () { //保存贫困户
            //其他贫困原因多选
            var arr = []
            var otherArr = $('#other input:checked')
            for (var i = 0; i < otherArr.length; i++) {
                arr.push(otherArr[i].value)
            }

            //帮扶责任人多选
            var helpArr = $('#helpTobdy input[name=help]')
            var arr1 = []
            if (helpArr.length) {
                helpArr.each(function (i, item) {
                    arr1.push($(item).attr('id'))
                })
            }

            var valid = modelForm.valid();
            var data = {
                province: $('#province1').val(),
                city: $('#city1').val(),
                county: $('#county').val(),
                country: $('#country').val(),
                village: $('#village1').val(),
                number: $('#number1').val(),
                contact: $('#contact').val(),
                bank: $('#bank').val(),
                cardNumber: $('#cardNumber').val(),
                standard: $('#standard').val(),
                poverty: $('#poverty').val(),
                attribute: $('#attribute').val(),
                soldier: $('#soldier1').val(),
                vehicle: $('#vehicle').val(),
                room: $('#room').val(),
                company: $('#company1').val(),
                reason: $('#reason input:checked').val() ? $('#reason input:checked').val() : '',
                other: arr.join(','),
                cuedLand: $('#cuedLand').val(),
                irrigation: $('#irrigation').val(),
                woodLand: $('#woodLand').val(),
                farmLand: $('#farmLand').val(),
                fruit: $('#fruit').val(),
                forageGrass: $('#forageGrass').val(),
                waters: $('#waters').val(),
                production: $('#production').val(),
                cooperative: $('#cooperative').val(),
                distance: $('#distance').val(),
                type: $('#type').val(),
                housing: $('#housing').val(),
                life: $('#life').val(),
                difficulty: $('#difficulty').val(),
                security: $('#security').val(),
                danger: $('#danger').val(),
                level: $('#level').val(),
                fuel: $('#fuel').val(),
                toilet: $('#toilet').val(),
                wages: $('#wages').val(),
                operating: $('#operating').val(),
                property: $('#property').val(),
                transfer: $('#transfer').val(),
                planning: $('#planning').val(),
                low: $('#low1').val(),
                five: $('#five').val(),
                pension: $('#pension').val(),
                ecology: $('#ecology').val(),
                elses: $('#elses').val(),
                year: $('#year1').val(),
                expenses: $('#expenses').val(),
                income: $('#income').val(),
                perCapita: $('#perCapita').val(),
                alone: $('#alone').val(),
                twoGirl: $('#twoGirl').val(),
                familys: JSON.stringify(memberArr),
                persons: arr1 ? arr1.join(',') : ''
            }

            if (isEdit) { //isEdit==1 表示编辑
                /*var id = $('#tbody input').eq(0).attr("id")*/
                var poorViId = mccms.getHash('id') //贫困户id
                data.id = poorViId
                var arr = []
                $('#tbody input').each(function (i, item) {
                    arr[i] = Number($(item).attr('id'))
                })
                data.familys = JSON.stringify(arr)
                data.addTime = addTime
                valid &&
                mccms.ajax({ //修改贫困户API
                    "url": "/poorFa/updatePoorFamily",
                    "cache": false,
                    "method": "POST",
                    "data": data,
                    "dataType": 'json',
                    "contentType": 'application/json',
                    "success": function () {
                        mccms.goBack()
                    }
                })


            } else { //isEdit 没有时表示新增
                var id = $('#tbody input').eq(0).attr("id")
                if (id) {
                    valid &&
                    mccms.ajax({ //新增贫困户API
                        "url": "/poorFa/addPoorFamily",
                        "cache": false,
                        "method": "POST",
                        "data": data,
                        "dataType": 'json',
                        "contentType": 'application/json',
                        "success": function () {
                            mccms.goBack()
                        }
                    })
                } else {
                    layer.msg('请添加家庭成员')
                }

            }

        },
        getW = function (params) { //省市县乡村

            //省请求
            _ajaxW(0, function (data) {
                createOption(data, function (cryHtml) {
                    $(".province1").each(function (i, item) {
                        $(item).html(cryHtml)
                    })
                    //省判断选中
                    $('.province1').val(s_province)
                    if (s_province) {
                        $('#province1').attr('disabled', 'disabled')
                    }
                    //市请求
                    _ajaxW(1, function (data) {
                        createOption(data, function (cryHtml) {
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                            //市判断选中
                            $('.city').val(s_city)
                            if (s_city) {
                                $('#city1').attr('disabled', 'disabled')
                            }
                            //县请求
                            _ajaxW(2, function (data) {
                                createOption(data, function (cryHtml) {
                                    $(".county").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                    //县判断选中
                                    $('.county').val(s_cty)
                                    if (s_cty) {
                                        $('#county').attr('disabled', 'disabled')
                                    }
                                    //乡请求
                                    _ajaxW(3, function (data) {
                                        createOption(data, function (cryHtml) {
                                            $('#country').html(cryHtml)
                                            $('#country').val(s_cry)

                                            //村请求
                                            if (s_cry) {
                                                $('#country').attr('disabled', 'disabled')
                                            }
                                            if (params) {
                                                $('#province1').val(params.province)
                                                $('#city1').val(params.city)
                                                $('#county').val(params.county)
                                                $('#country').val(params.country)
                                            }
                                            var countryId = $('#country').find('option:checked').attr('id');
                                            if (params) {
                                                // s_cry_id = countryId
                                            }
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                                $('.village1').val(s_name)
                                                if (s_name) {
                                                    $('#village1').attr('disabled', 'disabled')
                                                }
                                                if (params) {
                                                    $("#village1").val(params.village);
                                                }

                                                //村下拉
                                                $("#village1").change(function () {
                                                    village1Id = $(this).find("option:checked").attr("id");
                                                });

                                                var countryId = $('#country').find('option:checked').attr('id');
                                                if (params) {
                                                    /*s_cry_id = countryId*/
                                                }
                                                _ajaxW(countryId, function (data) {
                                                    createOption(data, function (cryHtml) {
                                                        $("#village1").html(cryHtml);
                                                    })
                                                    $('.village1').val(s_name)
                                                    if (s_name) {
                                                        $('#village1').attr('disabled', 'disabled')
                                                    }
                                                    if (params) {
                                                        $("#village1").val(params.village);
                                                    }
                                                    //村下拉
                                                    $("#village1").change(function () {
                                                        village1Id = $(this).find("option:checked").attr("id");
                                                    });
                                                })

                                            })
                                        })
                                    })
                                    if (s_cry) {
                                        $('#country').attr('disabled', 'disabled')
                                    } else {
                                        //乡下拉
                                        $("#country").change(function () {
                                            var countryId = $(this).find("option:checked").attr("id");
                                            //村请求
                                            _ajaxW(countryId, function (data) {
                                                createOption(data, function (cryHtml) {
                                                    $("#village1").html(cryHtml);
                                                })
                                            })
                                        });
                                    }
                                })
                            })
                        })
                    })
                })

                //省下拉
                $(".province1").change(function () {
                    var province1Id = $(this).find("option:checked").attr("id");
                    //市请求
                    _ajaxW(province1Id, function (data) {
                        createOption(data, function (cryHtml) {
                            // $("#city").html(cryHtml);
                            $(".city").each(function (i, item) {
                                $(item).html(cryHtml)
                            })
                        })
                    })
                    //市下拉
                    $(".city").change(function () {
                        var cityId = $(this).find("option:checked").attr("id");
                        //县请求
                        _ajaxW(cityId, function (data) {
                            createOption(data, function (cryHtml) {
                                // $("#county").html(cryHtml);
                                $(".county").each(function (i, item) {
                                    $(item).html(cryHtml)
                                })
                            })
                        })
                        //县下拉
                        $(".county").change(function () {
                            var countyId = $(this).find("option:checked").attr("id");
                            //乡请求
                            _ajaxW(countyId, function (data) {
                                createOption(data, function (cryHtml) {
                                    // $("#country").html(cryHtml);
                                    $(".country").each(function (i, item) {
                                        $(item).html(cryHtml)
                                    })
                                })
                            })
                            //乡下拉
                            $("#country").change(function () {
                                var countryId = $(this).find("option:checked").attr("id");


                                //村下拉
                                /*$("#village1").change(function() {
                                    village1Id = $(this).find("option:checked").attr("id");*/


                                //村请求
                                _ajaxW(countryId, function (data) {
                                    createOption(data, function (cryHtml) {
                                        $("#village1").html(cryHtml);
                                    })
                                })

                                //村下拉
                                $("#village1").change(function () {
                                    village1Id = $(this).find("option:checked").attr("id");
                                    getHelpPersonList();
                                });

                            });
                        });
                    });
                });
            })
        },
        _ajaxW = function (id, fn) { //地区请求
            mccms.ajax({
                "url": "/area/findarea",
                "cache": false,
                "method": "POST",
                "data": {
                    "fatherId": id
                },
                success: function (data) {
                    return fn(data)
                }
            });
        },
        createOption = function (data, fn) { //创造option
            var cryHtml = '<option value="">请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
            }
            return fn(cryHtml)
        }

    // 流程
    //家庭成员保存
    addMain.on('click', '#save1-btn', function () {
        subMemberMsg()
    })
    //全部保存
    addMain.on('click', '#save-btn', function () {
        myRequired("modelForm", "addPopup"); //必填提示
        subMsg()
    })

    var memberArr = [];

    //进入主页面时先删除家庭成员列表
    mccms.ajax({ //删除家庭成员API
        "url": "/poorFa/deleteFamily",
        "cache": false,
        "method": "POST",
        "data": '',
        success: function (data) {
        }
    });

    //页面加载
    //operatedState==1为查看不可编辑,0为可编辑
    if (operatedState == 1) { //查看页面
        getDetail(id)
    }
    if (operatedState == 0) { //编辑页面
        getDetail(id, addTime)
    }
    if (!id) { //新增页面
        getDetail()
    }
}

/*日志管理
  Devin  
  2017-12-5
*/
function journalMng() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null,
        getList = function (pageNo, pageSize, checkType) { //getList() 主页面渲染
            mccms.ajax({ //日志管理api
                "url": "/log/listLog",
                "cache": false,
                "method": "POST",
                "data": $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize,
                "success": function (data) {
                    var data = data;
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "mainList",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            //分页方法
                            PagingMethods(pageNo, pageSize, data, getList);

                            //点击数据项添加背景色
                            tdAddBg('table')

                            //获取乡下拉选中值编码
                            areaCodeInquire("cry")

                            //改变td line-height
                            $("#tbody tr td").css("line-height", "27px")

                        }
                    });
                }
            })

        };
    //起始日期
    dateFormat('start', 'datetime')
    //截止日期
    dateFormat('end', 'datetime')

    // 流程
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')
    });
    //初始化数据
    getList(pageNo, pageSize);
}

/*
  添加时间插件laydate
  Devin
  2017-12-5
  id  需要添加的时间插件的id
  type 时间格式  year-年 month-年月 date年月日 time-时、分、秒 datetime年、月、日、时、分、秒
    
*/
function dateFormat(id, type) {
    laydate.render({
        elem: '#' + id, //指定元素
        type: type, //年选择器
    })
}

/*
*用户管理  修改版
*Devin
 2017-12-11

*/

function new_userMsgEdit() {

    // 变量声明
    var id = mccms.getHash('id'), //用户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        operated2 = mccms.getHash('operated'), //1为查看不可编辑,0为可编辑
        form = $('#userForm'),
        path = $('.c-primary'),
        level,
        levelId, //等级选择id
        areaId = 0, //地区id，系统默认为0
        setUserToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/user/editUser/" + id,
                "cache": false,
                "method": "GET",
                "data": {
                    pageNo: 1,
                    pageSize: 100
                },
                success: function (data) {
                    var data = data || {

                            result: {},
                            user: {
                                roles: []
                            }
                        },
                        roles = data.result.user.roles;
                    data.result.detail = operated,
                        setForm(data.result, roles.length > 0 ? roles[0].id : 'eva')
                }
            })
        },
        setRoleToForm = function () {
            mccms.ajax({
                "url": "/role/getRoleAllFilter",
                "cache": false,
                "method": "GET",
                "data": {
                    pageNo: 1,
                    pageSize: 100
                },
                success: function (data) {
                    setForm({"add": 1, "role": data.result})
                    $('input[name="username"]').removeAttr("disabled");

                }
            })
        },
        getListGrade = function (pageNo) { //等级管理
            var pageNo;
            mccms.ajax({
                "url": "/userLevel/getUserLevelAll",
                "cache": false,
                "method": "GET",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": 8
                },
                "success": function (data) {
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "userList",
                        "container": $("#tbody"),
                        "data": data
                        // "callback" : function(){}
                    });
                    mccms.pageHtml(data, getListGrade, []);
                    //流程 
                    $('.ensure_btn').on('click', function () { //确定
                        // 选择等级---- 省市镇等 
                        var gradeName = $(this).parent().attr('data-name')
                        level = $(this).parent().attr('level') // 等级id--用于提交数据时用户所选等级
                        levelId = $(this).parent().attr('levelid') //等级i--用于获取相应的村选择范围
                        $('#grade').val(gradeName) //显示等级选择
                        $('#h-grade').val(levelId).attr('level', level) //获取等级id

                        //选择等级，清空原先地区所有选择值，重选
                        $('#area,#h-area,#keyword').val('')

                        $('.cover-show2').hide() //关闭等级窗口

                        if (level == 0) { //若等级为系统，则无地区可选择，禁止地区编辑
                            $('#area').attr('disabled', 'disabled')
                            $('#h-area').val('0') // 地区id默认为0
                        } else {
                            $('#area').removeAttr('disabled')
                        }

                        if (level == 0 || level == 1 || level == 2 || level == 3) { //乡村等级下，地区显示搜索框,否则隐藏
                            $('.show').hide()
                        } else {
                            $('.show').show()
                        }
                        if (level == 4) { //等级为乡镇
                            $('.areaName').text("乡名:")
                        }

                    })


                }
            })
        },
        getListArea = function (pageNo, id) { //地区管理
            var pageNo = pageNo || mccms.getHash('pageNo') || mccms.stepCache.pageNo,
                keyword = $('#keyword').val() || '', //村名
                levelArea = $('#h-grade').attr('level'); // 所选等级
            if ($('#grade').val()) { //若等级已选择
                mccms.ajax({ //获取地区范围选择
                    "url": "/area/getAllAreas",
                    "cache": false,
                    "method": "POST",
                    "data": {
                        "pageNo": pageNo,
                        "pageSize": 8,
                        "level": levelArea, //等级
                        "keyword": keyword //地区名
                    },
                    "success": function (data) {
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "userListArea",
                            "container": $("#tbodyArea"),
                            "data": data
                            // "callback" : function(){}
                        });
                        mccms.pageHtml(data, getListArea, []); //分页
                        $('.cover-show').show() // 地区弹出框
                        $('.ensure_btn').on('click', function () { // 选择地区----xx镇 xx乡等
                            var areaName = $(this).parent().attr('areaName')
                            areaId = $(this).parent().attr('areaid')
                            $('#area').val(areaName) //显示地区名
                            $('#h-area').val(areaId) //获取地区id
                            $('.cover-show').hide() //关闭地区弹窗
                        });

                    }
                })
            } else {
                layer.msg('请选择等级')
            }

        },
        setForm = function (data, checkedId) { //填充表单
            var data = data || {};
            mccms.getHbs({
                "local": true,
                "hbsName": "userMsg",
                "container": form,
                "data": data,
                "callback": function () {
                    //如果当前登录用户等级不够则禁选admin
                    if (userLevel > 3) {
                        $('#role1').attr('disabled', 'disabled');
                    }
                    var txt = operated ? '查看用户信息' : '编辑用户信息';
                    if (!checkedId) {
                        // $('.radio-box input[type="radio"]').eq(0).iCheck('check')
                    }
                    $('#grade').focus(function () { //选择等级
                        getListGrade()
                        $('.cover-show2').show()
                    })

                    $('#area').focus(function () { //选择地区
                        getListArea()
                    })

                    $('.queryBtn').on('click', function () { //绑定地区查询
                        getListArea()
                    })


                    id && path.html(txt), //修改模块名称
                        $('.radio-box input[type="radio"]').iCheck({
                            checkboxClass: 'icheckbox-blue',
                            radioClass: 'iradio-blue',
                            increaseArea: '20%'
                        }),
                    checkedId !== 'eva' && $('#role' + checkedId).iCheck('check'),
                        form.mcFormValide() //绑定表单验证     
                }
            })
        },
        subMsg = function (ele) { //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/user/updateUserInfo" : "/user/addUser",
                name = $("#username").val(); //用户名
            if (operated2 == '') { //新增状态下
                mccms.ajax({ //重名校验API
                    "url": "/user/verifyUsername",
                    "cache": false,
                    "method": "POST",
                    "data": {"username": name},
                    "success": function (duplicationData) {
                        if (duplicationData.result) { //用户名重名时
                            layer.msg("此用户名已存在,请重新输入！");
                        } else { //用户名不重名
                            if ($('#h-area').val()) {

                                valid &&
                                mccms.ajax({
                                    "url": url,
                                    "data": data,
                                    "lock": true,
                                    "cache": true,
                                    "beforeSend": function () {
                                        ele && ele.attr('disabled', 'disabled');
                                    },
                                    "complete": function () {
                                        ele && ele.removeAttr('disabled');
                                    },
                                    "success": function (data) {
                                        layer.msg(data.message)
                                        mccms.goBack()
                                    }
                                })
                            } else {
                                layer.msg('请选择地区')
                            }

                        }
                    }
                })
            } else { //编辑状态下，不进行重名校验
                if ($('#h-area').val()) {

                    valid &&
                    mccms.ajax({
                        "url": url,
                        "data": data,
                        "lock": true,
                        "beforeSend": function () {
                            ele && ele.attr('disabled', 'disabled');
                        },
                        "complete": function () {
                            ele && ele.removeAttr('disabled');
                        },
                        "success": function (data) {
                            layer.msg(data.message)
                            mccms.gobackFromEdit()
                        }

                    })
                } else {
                    layer.msg('请选择地区')
                }
            }
        };

    // 流程
    $("#goUserMng").on("click", function () { //跳转至用户管理
        mccms.goTo("user_msg", "user_management");
    })
    $('.close_btn').on('click', function () { // 关闭弹窗
        $('.cover-div').hide()
    })
    id ? setUserToForm() : setRoleToForm(), //新增或编辑查看
        form.on('click', '.sub_btn', function () {

            subMsg($(this))
        })

}

/*
    智能街景--贫困村
    bill
    2018-005-15
*/
function povertyVista() {
    var cryVal = s_cry,
        nameVal = s_name,
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                cryAndNameChange()
            })
        };
    getList()

    //村选中加载时间数据
    $("#name").change(function () {
        nameId = $(this).find("option:checked").attr("id");
        nameVal = $(this).find("option:checked").val();
        $("#h-name").val($(this).find("option:checked").attr("data-number"))
        $("#h-nameval").val($(this).find("option:checked").attr("id"));
        $("#h-time").val("") //清空时间值
        mccms.ajax({
            "url": "/vision/listDate",
            "cache": false,
            "method": "GET",
            "data": {
                "villageID": nameId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + ' " value="' + data.result[i] + '">' + data.result[i] + '</option>';
                }
                $("#time").html(naturalsHtml);
            }
        });
    });

    //时间选中加载链接地址数据
    $("#time").change(function () {
        var nameId = $("#h-nameval").val();
        var timeVal = $(this).find("option:checked").val();
        $("#h-time").val($(this).find("option:checked").attr("data-number"))
        $("#h-link").val("") //清空链接地址值
        mccms.ajax({
            "url": "/vision",
            "cache": false,
            "method": "GET",
            "data": {
                "date": timeVal,
                "villageID": nameId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + ' " value="' + data.result[i].resource + '">' + data.result[i].resource + '</option>';
                }
                $("#link").html(naturalsHtml);
            }
        });
    });

    //链接地址选中加载链接地址数据
    $("#link").change(function () {
        linkVal = $(this).find("option:checked").val(); //村名
        $("#h-link").val(linkVal);
        $("link").val(linkVal) //村回显

    });

    //流程
    $('.examine').on('click', function () {
        var linkval = $('#h-link').val();
        console.log(linkval)
        showVista('iframe', linkval)
    })
    /*showVista('iframe', 'http://i.svrvr.com/?a=wapview&id=y89619&code=003LbAi72qJefL0eNzj72CcJi72LbAiJ&state=blinq')*/
}

/*
防贫预警
bill
*/
function preventPoverty() {
    var cryVal = s_cry,
        nameVal = s_name,
        getlist = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                cryAndNameChange()
            })
        };
    getlist()


    function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

        return Y + M + D;
    }


    var main = $('#MainList'),
        //_id = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            //获取输入框的值
            var type = $("#type").find("option:checked").text();
            var country = $("#cry").find("option:checked").text();
            var village = $("#name").find("option:checked").text();
            var target = $("#h-target").val();
            if (type == "请选择" || type == "全部") {
                type = "";
            }
            if (country == "请选择" || country == "全部") {
                country = "";
            }
            if (village == "请选择" || village == "全部") {
                village = "";
            }

            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/prevent/list",
                "cache": false,
                "method": "GET",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": pageSize,
                    "type": type,
                    "country": country,
                    "village": village,
                    "target": target
                },
                "success": function (data) {
                    for (var i = 0; i < data.result.resultList.length; i++) {
                        data.result.resultList[i].warningTime = timestampToTime(parseInt(data.result.resultList[i].warningTime))
                        console.log(data.result.resultList[i].warningTime)
                    }
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {
                            $(".goto").on("click", function () { //查看
                                var id = $(this).attr('id'); //用户ID
                                mccms.goTo("preventPoverty", "povertyStrickenEdit", {"id": id, "operatedState": 1, "detail": 1}); //operatedState==1为查看不可编辑,0为可编辑
                            })


                            $("#tbody tr").each(function () {
                                $(this).find("td").eq(0).text($(this).index() + 1)
                            })
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    if (i == 'fatherId') {
                                        $('#country option').each(function () {
                                            if ($(this).attr('id') == prevFrom[i]) {
                                                $(this).attr('selected', 'selected')
                                            }
                                        })
                                    }
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });
                }
            })
        }


    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "fatherId": $('#fatherId').val(),
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    $(".btn-secondary").on("click", function () {
        getList(pageNo, pageSize)
    })


    $(".btn-export").on("click", function () {
        //获取输入框的值
        var type = $("#type").find("option:checked").text();
        var country = $("#cry").find("option:checked").text();
        var village = $("#name").find("option:checked").text();
        var target = $("#h-target").val();
        if (type == "请选择" || type == "全部") {
            type = "";
        }
        if (country == "请选择" || country == "全部") {
            country = "";
        }
        if (village == "请选择" || village == "全部") {
            village = "";
        }

        var address = window.location.pathname.split("/");
        if (address[1] == "welcome") {
            address[1] = "";
        }
        var hostport = document.location.host;
        var pro = document.location.protocol;
        var url = hostport + "/" + address[1];
        window.location.href = pro + "//" + url + "/prevent/export?pageNo=" + pageNo + "&pageSize=" + pageSize + "&type=" + type + "&country=" + country + "&village=" + village + "&target=" + target;
    })
}

/*
    智能街景--贫困户搜索
    bill
    2018-05-15
*/
function poorVista() {
    var cryVal = s_cry,
        nameVal = s_name,
        getSearch = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                cryAndNameChange()
            })
        };
    getSearch()

    var main = $('#MainList'),
        //_id = null,
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        getList = function (pageNo, pageSize) {
            //获取输入框的值
            var country = $("#cry").find("option:checked").text();
            var village = $("#name").find("option:checked").text();
            var poorName = $("#poorName").val();
            var poorFamilyNum = $("#poorFamilyNum").val();
            if (country == "请选择" || country == "全部") {
                country = "";
            }
            if (village == "请选择" || village == "全部") {
                village = "";
            }
            if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                backFrom = sessionStorage.getItem('from')
            } else { //刷新时，重置查询条件
                backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
            }
            mccms.ajax({
                "url": "/poorFa/findPoorFamilyByCondition",
                "cache": false,
                "method": "GET",
                "data": {
                    "pageNo": pageNo,
                    "pageSize": pageSize,
                    "village": village,
                    "country": country,
                    "poorName": poorName,
                    "poorFamilyNum": poorFamilyNum
                },
                "success": function (data) {
                    console.log(data)
                    mccms.getHbs({
                        "local": true,
                        "hbsName": "list",
                        "container": $("#tbody"),
                        "data": data.result,
                        "callback": function () {

                            $('.del_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                            });

                            $('.view_btn').on('click', function () {
                                var id = $(this).parents('td').attr('id');
                                var resource = $(this).parents('td').parents('tr').find("td").eq(2).text();
                                mccms.goTo("poorVista", "poorVista_show", {"id": id});
                            });


                            $("#tbody tr").each(function () {
                                $(this).find("td").eq(0).text($(this).index() + 1)
                            })
                            if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                var pageNo3 = sessionStorage.getItem('pageNo2'),
                                    pageSize3 = sessionStorage.getItem('pageSize2'),
                                    prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                //显示原先的查询条件
                                for (var i in prevFrom) {
                                    if (i == 'fatherId') {
                                        $('#country option').each(function () {
                                            if ($(this).attr('id') == prevFrom[i]) {
                                                $(this).attr('selected', 'selected')
                                            }
                                        })
                                    }
                                    $('#' + i).val(prevFrom[i])
                                }
                                //分页方法
                                PagingMethods(pageNo3, pageSize3, data, getList);

                            } else {
                                //分页方法
                                PagingMethods(pageNo, pageSize, data, getList);
                            }
                            //删除从查看、编辑页面返回的标记,不然刷新会有问题
                            sessionStorage.removeItem("backId");
                        }
                    });
                }
            })
        }
    // 流程
    $('.add_btn').on('click', function () {
        mccms.goTo("povertyStrickenMng_street", "povertyStrickenMng_street_msg", {"villageID": _id, "operated": 0, "country": country, "village": village});
    });

    main.on('click', '.detail_btn', function () {
        var id = $(this).parents('td').attr('id');
        var fatherId = $(this).parents('td').attr('attr-fatherId');
        mccms.goTo("villageMng", "villageMng_msg", {"id": id, "fatherId": fatherId, "operated": 1});
    });
    $(".search-btn").on("click", function () {
        getList(pageNo, pageSize)
    })


    //进入查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "fatherId": $('#fatherId').val(),
            "areaCode": $('#areaCode').val(),
            "area": $('#area').val()
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)
}

/*智能街景--贫困户搜索 end*/


/*
智能街景--贫困户街景查看
bill
2018-05-15
*/
function poorVistaShow() {

    // 变量声明
    var nameId = mccms.getHash('id') //用户id

    mccms.ajax({
        "url": "/poolVision/listDate",
        "cache": false,
        "method": "GET",
        "data": {
            "poolFamilyId": nameId
        },
        success: function (data) {
            console.log(data)
            var naturalsHtml = '<option value="" selected>请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                naturalsHtml += '<option data-number="' + data.result[i].areaCode + ' " value="' + data.result[i] + '">' + data.result[i] + '</option>';
            }
            $("#time").html(naturalsHtml);
        }
    });


//时间选中加载链接地址数据
    $("#time").change(function () {
        var timeVal = $(this).find("option:checked").val();
        $("#h-time").val($(this).find("option:checked").attr("data-number"))
        $("#h-link").val("") //清空链接地址值
        mccms.ajax({
            "url": "/poolVision",
            "cache": false,
            "method": "GET",
            "data": {
                "date": timeVal,
                "poolFamilyId": nameId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + ' " value="' + data.result[i].resource + '">' + data.result[i].resource + '</option>';
                }
                $("#link").html(naturalsHtml);
            }
        });
    });

//链接地址选中加载链接地址数据
    $("#link").change(function () {
        linkVal = $(this).find("option:checked").val(); //村名
        $("#h-link").val(linkVal);
        $("link").val(linkVal) //村回显

    });

//流程
    $('.examine').on('click', function () {
        var linkval = $('#h-link').val();
        console.log(linkval)
        showVista('iframe', linkval)
    })
}

/*智能街景--贫困户街景查看 end*/

/*
    展示街景
    id: ifraem的id
    url 要展示的内容链接
*/
function showVista(id, url) {
    var ele = document.getElementById(id)
    ele.src = url;
}

/*
app配置
*/
function appConfig() {
    $(".app-nav-startup").on("click", function () { //跳转至用户管理
        mccms.goTo("app_config", "app_config_startup");
    })
}

/*
app启动页面
*/
function appConfigStartup() {
    mccms.ajax({
        "url": "/app/listStartupIMG",
        "cache": false,
        "method": "POST",
        "success": function (data) {
            console.log(data)
            for (var i = 0; i < data.result.length; i++) {
                $(".upload-show").eq(i).attr("src", data.result[i].url)
                $(".edit-id").eq(i).val(data.result[i].id)
            }
        }
    })
    $("#bill-submit").on("click", function () {
        /*        if($(".upload").eq(0).val()&&$(".upload").eq(1).val()&&$(".upload").eq(2).val()) {
                    layer.msg($(".upload").eq(num).val());
                    return ;
                }*/
        var form = $(".bill-startup-form");
        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: new FormData(document.getElementsByClassName("bill-startup-form")[0]),
            mimeType: "multipart/form-data",
            contentType: false,
            cache: false,
            processData: false
        }).success(function (data) {
            layer.msg("操作成功");
        })

    })
}

function doSelectPhotoChanged(ele, num) {
    var filesize = ele.files[0].size;
    var file = $(".upload").eq(num).val();
    var filetype = file.substr(file.indexOf("."));
    if (filetype != '.jpg' && filetype != '.png' && filetype != '.gif' && filetype != '.JPG' && filetype != '.PNG') {
        layer.msg("上传的图片类型不对,请重新上传");
        $(".upload").eq(num).val("");
        return;
    } else if (filesize / 1024 > 500) {
        layer.msg("上传的图片不能大于500K,请重新上传");
        $(".upload").eq(num).val("");
        return;
    }
    var filePath = ele.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(filePath);
    reader.onload = function (e) {
        $(".upload-show").eq(num).attr("src", this.result)
    }
}

/*年度数据备份*/
function annualDataBackup() {

    // var origin = {
    //     elem: '#origin',
    //     format: 'YYYY',
    //     max: businessAnnual,
    //     istime: false,
    //     istoday: false
    // };
    // var derivation = {
    //     elem: '#derivation',
    //     format: 'YYYY',
    //     max: businessAnnual+1,
    //     istime: false, //是否开启时间选择
    //     istoday: false,
    //     isclear: true, //是否显示清空
    //     issure: true, //是否显示确认
    // };
    // laydate(origin);
    // laydate(derivation);

    // laydate.render({
    //     elem: '#origin',
    //     type: 'year',
    //     value: businessAnnual
    //
    // })
    // laydate.render({
    //     elem: '#derivation',
    //     type: 'year',
    //     value: parseInt(businessAnnual)+1
    // })
    $('#origin').val(businessAnnual);
    $('#derivation').val(parseInt(businessAnnual) + 1);

    /*备份功能*/
    function backup() {
        var originY = $("#origin").val();//? $("#origin").val() : $("#derivation").val() ? parseInt($("#derivation").val()) - 1 : new Date().getFullYear(); //源数据年度
        var derivationY = $("#derivation").val();// ? $("#derivation").val() : $("#origin").val() ? parseInt($("#origin").val()) + 1: new Date().getFullYear() + 1; //目标年度
        console.log(originY, derivationY)
        var tips = "<h3>是否确认备份？</h3>"
            + "<p>源数据年度 : " + originY + " 年度</p>"
            + "<p>目标年度 : " + derivationY + " 年度</p>"
            + "<p id='backupProgressInfo'></p>";
        //询问框
        layer.confirm(tips, {
            btn: ['确定', '取消'] //按钮
        }, function () {
            mccms.ajax({ //备份API
                "url": "/annualBackup",
                "cache": false,
                "method": "POST",
                "data": $("#searchForm").serialize(),
                "success": function (data) {
                    switch (data.status) {
                        case '200':
                            if (data.result.poorVillage == "备份成功"
                                && data.result.family == "备份成功"
                                && data.result.poorFamily == "备份成功") {
                                layer.msg("备份成功!")
                            } else {
                                layer.msg("备份失败，请重新备份!")
                            }
                            break;
                        case '400':
                            layer.msg(data.message)
                            if (data.message == '当前正在备份') {
                                layer.open({
                                    type: 1,
                                    title: "备份详情",
                                    area: ['300px', '120px'], //宽高
                                    content: "<p id='backupProgressInfo2'></p>"
                                });
                                var scheduler2 = setInterval(function () {
                                    mccms.ajax({ //备份进度
                                        "url": "/getBackupProgress",
                                        "cache": false,
                                        "method": "POST",
                                        "success": function (data) {
                                            if (data && data.result) {
                                                $('#backupProgressInfo2').text('已完成：' + data.result.progress + '  状态：' + data.result.info);
                                            } else {
                                                clearInterval(scheduler2);
                                            }
                                        }
                                    });
                                }, 900);
                            }
                            break;
                        case '500':
                            layer.msg("操作失败，请回滚后，重新备份！")
                        default:
                            layer.msg("备份失败，请重新备份!")

                    }
                }
            });
            var scheduler = setInterval(function () {
                mccms.ajax({ //备份进度
                    "url": "/getBackupProgress",
                    "cache": false,
                    "method": "POST",
                    "success": function (data) {
                        if (data && data.result) {
                            $('#backupProgressInfo').text('已完成：' + data.result.progress + '  状态：' + data.result.info);
                        } else {
                            clearInterval(scheduler);
                        }
                    }
                });
            }, 900);

        }, function () {
            layer.msg('取消备份！')
        })


    }

    /*回滚功能*/
    function rollback() {
        //询问框
        layer.confirm('是否回退上一次备份操作（不可撤销）？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            mccms.ajax({ //回滚API
                "url": "/restore",
                "cache": false,
                "method": "POST",
                "success": function (data) {
                    layer.msg(data.message)
                }
            })
        }, function () {
            layer.msg('取消回退！')
        })


    }

    //流程
    $(".backupBtn").on("click", function () { //备份
        if (!$("#origin").val()) {
            layer.msg("请填写源数据年度")
            return;
        }
        if (!$("#derivation").val()) {
            layer.msg("请填写目标年度")
            return;
        }
        if ($("#origin").val() >= $("#derivation").val()) {
            layer.msg("源数据年度需小于目标年度")
            return;
        }
        backup()
    })
    $(".rollbackBtn").on("click", function () { //回滚
        rollback()
    })

}

/*--项目库管理--*/
function projectLibraryManager() {
    // 变量声明
    var main = $('#memberManage'),
        cryVal = s_cry, //乡的选中
        nameVal = s_name, //县的选中
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        backFrom, //进入编辑、查看页面时，主页面的查询条件
        countryName, //村名
        getList = function (pageNo, pageSize, checkType) {
            areaSelected(cryVal, nameVal, checkType, function () {
                if (sessionStorage.getItem('backId') == 1) { //从编辑、查看页面返回时，根据原先的查询条件查询
                    backFrom = sessionStorage.getItem('from')
                } else { //刷新时，重置查询条件
                    backFrom = $("#searchForm").serialize() + "&pageNo=" + pageNo + "&pageSize=" + pageSize
                }
                mccms.ajax({
                    "url": "/company/queryCompanyList",
                    "cache": false,
                    "method": "POST",
                    "data": backFrom,
                    "success": function (data) {
                        var data = data;
                        mccms.getHbs({
                            "local": true,
                            "hbsName": "List",
                            "container": $("#tbody"),
                            "data": data.result,
                            "callback": function () {
                                if (sessionStorage.getItem('backId') == 1) { //查看编辑页面返回，回显原先的查询页码和每页数据条
                                    var pageNo3 = sessionStorage.getItem('pageNo2'),
                                        pageSize3 = sessionStorage.getItem('pageSize2'),
                                        prevFrom = JSON.parse(sessionStorage.getItem('prevFrom'));
                                    //显示原先的查询条件
                                    for (var i in prevFrom) {
                                        if (i == 'cry') {
                                            $('#' + i).val(prevFrom[i]).trigger('change')
                                        } else if (i == 'name') {
                                            /*$('#' + i).find('option:selected').text(prevFrom[i])*/
                                            countryName = prevFrom[i]
                                        } else {
                                            $('#' + i).val(prevFrom[i])
                                        }
                                    }

                                    /*$('#name').find('option:selected').text(countryName) //回显村名*/
                                    //分页方法
                                    PagingMethods(pageNo3, pageSize3, data, getList);

                                } else {
                                    //分页方法
                                    PagingMethods(pageNo, pageSize, data, getList);
                                }
                                //删除从查看、编辑页面返回的标记,不然刷新会有问题
                                sessionStorage.removeItem("backId");

                                //点击数据项添加背景色
                                tdAddBg('tbody')

                                laydate.render({
                                    elem: '#year', //指定元素
                                    type: 'year'
                                })
                                //乡回显
                                if (cryVal) {
                                    $('#cry').val(cryVal)

                                }
                            }
                        });

                    }
                })
            });
        };

    //乡选中加载村数据
    $("#cry").change(function () {
        cryId = $(this).find("option:checked").attr("id");
        cryVal = $(this).find("option:checked").val();
        $("#h-cry").val($(this).find("option:checked").attr("data-number"))
        $("#h-village").val("") //清空村值
        mccms.ajax({
            "url": "/area/findarea",
            "cache": false,
            "method": "POST",
            "data": {
                "fatherId": cryId
            },
            success: function (data) {
                var naturalsHtml = '<option value="" selected>请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                }
                $("#village").html(naturalsHtml);
                if (countryName) {
                    $("#village option").each(function (ele) {
                        if ($(this).text() == countryName) {
                            $(this).attr('selected', 'selected')
                        }

                    })
                }
            }
        });
    });
    //村选中加载村数据
    $("#village").change(function () {
        nameVal = $(this).find("option:checked").val(); //获取乡选中值，如果不获取，页面查询后，页面该值显示为空
        s_name_id = $(this).find("option:checked").attr("data-number");
        $("#h-village").val(s_name_id);
    });

    ThisYear(); //备份当前年
    // 流程
    main.on('click', '.add_btn', function () { //新增
        mccms.goTo("projectLibraryManager", "projectLibraryEdit");
    });
    main.on('click', '.detail_btn', function () { //查看
        var id = $(this).parents('td').attr('id');
        mccms.goTo("projectLibraryManager", "projectLibraryEdit", {"id": id, "operated": 1});
    });
    main.on('click', '.edit_btn', function () { //编辑
        var id = $(this).parents('td').attr('id');
        mccms.goTo("projectLibraryManager", "projectLibraryEdit", {"id": id, "operated": 0});
    });
    main.on('click', '.del_btn', function () { //删除
        var id = $(this).parents('td').attr('id');
        mccms.operation({
            "method": "delete",
            "name": '删除',
            "url": "/company/delCompanyById?id=" + id,
            "sub": true,
            "fn": function () {
                /* layer.msg("删除成功！")*/
                getList(pageNo, pageSize)
            }
        })
    });
    main.on('click', '.queryBtn', function () { //查询
        getList(pageNo, pageSize, 'true')

    });
    main.on('click', '.refresh_btn', function () { //刷新
        getList();
    });

    //进入编辑、查看页面前，保留查询条件
    main.on('click', '.save_from', function () {
        var pageNo2 = $('#pageCount').val(),
            pageSize2 = $('#pageSize').val()
        prevFrom = {
            "cry": $('#cry').val(),
            "name": $('#name').val(),
            "company": $('#company').val(),
            "founder": $('#legal_person').val(),
        };
        sessionStorage.setItem('pageNo2', pageNo2)
        sessionStorage.setItem('pageSize2', pageSize2)
        sessionStorage.setItem('from', $("#searchForm").serialize() + "&pageNo=" + pageNo2 + "&pageSize=" + pageSize2)
        sessionStorage.setItem('prevFrom', JSON.stringify(prevFrom))

    })
    getList(pageNo, pageSize)

}

/*-- 项目库新增、编辑、查看方法 --*/
function projectLibraryEdit() {
    var id = mccms.getHash('id'), //用户id
        operated = mccms.getHash('operated') ? parseInt(mccms.getHash('operated')) : 0, //1为查看不可编辑,0为可编辑
        inquire = mccms.getHash('inquire'), //inquire: 1,表示从《账表查询》过来
        form = $('#editForm'),
        path = $('.c-primary'),
        pageNo = 1, //当前第1页
        pageSize = 10, //每页10行
        pageCount = null, //总页数
        setNoticeToForm = function () { //获取用户数据
            mccms.ajax({
                "url": "/company/queryCompanyById?id=" + id,
                "cache": false,
                "method": "POST",
                success: function (data) {
                    var data = data || {
                        result: {}
                    };
                    data.result.detail = operated,
                        setForm(data.result);
                }
            })
        },
        setAddToForm = function () {
            setForm();
            /*定位锚点，点击导航栏跳转到指定位置*/
            /* scrollToBox('nav_item')*/
        },
        setForm = function (data) { //填充表单
            var country = [],
                village = [],
                cryId;
            var data = data || {};
            if (data.resultList) {
                data = data.resultList[0];
            }
            mccms.getHbs({
                "local": true,
                "hbsName": "editList",
                "container": form,
                "data": data,
                "callback": function () {
                    if (inquire == 1) { //inquire == 1从《账表查询》过来则修改模块名称
                        $("nav .menuLevel1").html("账表查询");
                        $("nav .menuLevel2").html("自然村查询");
                        $("nav .c-primary").html("查看项目");
                    }
                    $(".upload-show").attr("src", data.legal_person_pic);
                    $(".edit-id").val(data.legal_person_pic);
                    var txt = operated ? '查看项目' : '编辑项目';
                    id && path.html(txt), //修改模块名称
                        form.mcFormValide() //绑定表单验证
                    //就业名单加载
                    if (id) {
                        getList = function (pageNo, pageSize) {
                            mccms.ajax({
                                "url": "/company/queryCompanyFamilyById",
                                "cache": false,
                                "method": "POST",
                                "data": {
                                    "pageNo": pageNo,
                                    "pageSize": pageSize,
                                    "id": 1
                                },
                                "success": function (data) {
                                    mccms.getHbs({
                                        "local": true,
                                        "hbsName": "List1",
                                        "container": $("#tbody1"),
                                        "data": data.result,
                                        "callback": function () {
                                            //分页方法
                                            PagingMethods(pageNo, pageSize, data, getList)
                                            //分页样式
                                            $("#pageContainer select").css({
                                                'width': '100%',
                                                'height': 'auto'
                                            })
                                        }
                                    })

                                }
                            })

                        }
                        getList(pageNo, pageSize)
                    }

                    if (operated == 1) {
                        $(".keepBtnBox").hide();
                    }

                    /*定位锚点，点击导航栏跳转到指定位置*/
                    scrollToBox('nav_item')
                    /**
                     * 模板加载后，获取到select框的值，给页面加载选中状态
                     *
                     */
                    var countryVal, //定义乡
                        natrueVal; //定义村

                    if (s_cry || s_name) {
                        countryVal = s_cry;
                        natrueVal = s_name;
                    }
                    if (data.country) {
                        countryVal = data.country; //获取到乡的值 
                    }
                    if (data.village) {
                        natrueVal = data.village; //获取到自然村的值  
                    }

                    //10-11 wage add 地区三级联动select填充
                    mccms.ajax({
                        "url": "/area/findarea",
                        "cache": false,
                        "method": "POST",
                        "data": {
                            "fatherId": 3 //3代表魏县的id
                        },
                        success: function (data) {

                            var cryHtml = '<option value="" selected>请选择</option>';
                            for (var i = 0; i < data.result.length; i++) {
                                cryHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                            }

                            $("#cry-add").html(cryHtml);

                            //编辑和查看下地区select框的填充
                            if (countryVal) { //乡的值填充
                                $("#cry-add option").each(function (i) {
                                    if ($(this).val() == countryVal) {
                                        $(this).attr("selected", "selected");
                                        $("#editForm #s-cry-add").val($(this).val());
                                        if (s_Level == 4 || s_Level == 5) {
                                            $("#cry-add").attr("disabled", "disabled");
                                        }
                                        cryId = $(this).attr("id"); //获取乡的选中值用来加载村的数据

                                        mccms.ajax({
                                            "url": "/area/findarea",
                                            "cache": false,
                                            "method": "POST",
                                            "data": {
                                                "fatherId": cryId
                                            },
                                            success: function (data) {
                                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                                for (var i = 0; i < data.result.length; i++) {
                                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                                }
                                                $("#natrueName-add").html(naturalsHtml);

                                                if (natrueVal) { //村的值填充
                                                    $("#natrueName-add option").each(function (i) {
                                                        if ($(this).val() == natrueVal) {

                                                            if (s_Level == 4 || s_Level == 5) {
                                                                $("#cry-add").attr("disabled", "disabled");
                                                            }
                                                            $(this).attr("selected", "selected");

                                                            $("#s-natrueName-add").val($(this).val());
                                                            if (s_Level == 5) {
                                                                $("#natrueName-add").attr("disabled", "disabled");
                                                            }
                                                            var natrueNum = $(this).attr("data-number"); //选中村之后，自动填充村编号
                                                            var natureId = $(this).attr("id");
                                                            $("#code").val(natrueNum);
                                                            $("#natureId").val(natureId);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        }


                    });


                    $("#cry-add").change(function () {
                        cryId = $(this).find("option:checked").attr("id");
                        $("#s-cry-add").val($(this).find("option:checked").val());
                        mccms.ajax({
                            "url": "/area/findarea",
                            "cache": false,
                            "method": "POST",
                            "data": {
                                "fatherId": cryId
                            },
                            success: function (data) {
                                var naturalsHtml = '<option value="" selected>请选择</option>';
                                for (var i = 0; i < data.result.length; i++) {
                                    naturalsHtml += '<option data-number="' + data.result[i].areaCode + '" id="' + data.result[i].id + '" value="' + data.result[i].area + '">' + data.result[i].area + '</option>';
                                }
                                $("#natrueName-add").html(naturalsHtml);
                            }
                        });

                    });
                    $("#natrueName-add").change(function () {
                        natrueNum = $(this).find("option:checked").attr("data-number"); //选中村之后，自动填充村编号
                        var natureId = $(this).find("option:checked").attr("id");
                        $("#natureId").val(natureId);
                        $("#s-natrueName-add").val($(this).find("option:checked").val());
                        $("#code").val(natrueNum);
                        $("#code").attr("readonly", "readonly");
                    });
                    //10-11 wage add
                }
            })
        },

        subMsg = function (ele) {debugger //提交用户数据
            var data = form.serialize(),
                valid = form.valid(),
                url = id ? "/company/editCompany" : "/company/addCompany"; //前者编辑API，后者新增API
            var company_name = $("#company_name").val();
            valid && $.ajax({
                "url": '/company/checkCompanyName',
                "data": {
                    "company_name": company_name
                },
                async: false,
                "method": "POST",
                "success": function (checkMsg) {
                    if (checkMsg.status == '500' && !id) {
                        layer.msg("该企业名称已经存在！");
                    } else {
                        valid && $.ajax({
                            type: 'post',
                            url: url,
                            data: new FormData(document.getElementsByClassName("form form-horizontal responsive")[0]),
                            mimeType: "multipart/form-data",
                            contentType: false,
                            cache: false,
                            processData: false
                        }).success(function (imgMsg) {
                            if (JSON.parse(imgMsg).status == '200') {
                                layer.msg("保存成功");
                                id ? mccms.gobackFromEdit() : mccms.goBack()
                            } else {
                                layer.msg("保存失败");
                            }
                        })
                    }
                }
            });

            if (!valid) {
                layer.msg("法人姓名或企业代码为空");
            }
        };
    // 流程
    id ? setNoticeToForm() : setAddToForm(),
        form.on('click', '.sub_btn', function () {
            myRequired("editForm", "popup");
            subMsg($(this));
        })

}







